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 |
|---|---|---|---|---|
live_timers.rs | use std::collections::HashMap;
use platform::time::time_now;
use super::StartTime;
use super::Timing;
#[derive(Debug, Clone, PartialEq)]
pub struct LiveTimers {
timers: HashMap<String, StartTime>,
}
impl LiveTimers {
pub fn | () -> LiveTimers {
LiveTimers { timers: HashMap::new() }
}
pub fn get_timers(&self) -> &HashMap<String, StartTime> {
&self.timers
}
pub fn start(&mut self, name: &str) -> StartTime {
let start_time = time_now();
self.timers.insert(name.to_string(), start_time.clone());
start_time
}
pub fn stop(&mut self, name: &str) -> Timing {
let stop_time = time_now();
let opt = self.timers.remove(name);
if opt.is_none() {
panic!("Tried to stop non-live timer: {:?}", name);
}
let start_time = opt.unwrap();
let duration = stop_time - start_time;
Timing::new(name, start_time, duration)
}
}
| new | identifier_name |
live_timers.rs | use std::collections::HashMap;
use platform::time::time_now;
use super::StartTime;
use super::Timing;
#[derive(Debug, Clone, PartialEq)]
pub struct LiveTimers {
timers: HashMap<String, StartTime>,
}
impl LiveTimers {
pub fn new() -> LiveTimers {
LiveTimers { timers: HashMap::new() }
}
pub fn get_timers(&self) -> &HashMap<String, StartTime> {
&self.timers
}
pub fn start(&mut self, name: &str) -> StartTime {
let start_time = time_now();
self.timers.insert(name.to_string(), start_time.clone());
start_time
}
pub fn stop(&mut self, name: &str) -> Timing {
let stop_time = time_now();
let opt = self.timers.remove(name);
if opt.is_none() |
let start_time = opt.unwrap();
let duration = stop_time - start_time;
Timing::new(name, start_time, duration)
}
}
| {
panic!("Tried to stop non-live timer: {:?}", name);
} | conditional_block |
live_timers.rs | use std::collections::HashMap;
use platform::time::time_now;
use super::StartTime;
use super::Timing;
#[derive(Debug, Clone, PartialEq)]
pub struct LiveTimers {
timers: HashMap<String, StartTime>,
}
impl LiveTimers {
pub fn new() -> LiveTimers {
LiveTimers { timers: HashMap::new() }
}
pub fn get_timers(&self) -> &HashMap<String, StartTime> |
pub fn start(&mut self, name: &str) -> StartTime {
let start_time = time_now();
self.timers.insert(name.to_string(), start_time.clone());
start_time
}
pub fn stop(&mut self, name: &str) -> Timing {
let stop_time = time_now();
let opt = self.timers.remove(name);
if opt.is_none() {
panic!("Tried to stop non-live timer: {:?}", name);
}
let start_time = opt.unwrap();
let duration = stop_time - start_time;
Timing::new(name, start_time, duration)
}
}
| {
&self.timers
} | identifier_body |
test_page_api.py | # coding: utf-8
"""
MailMojo API
v1 of the MailMojo API # noqa: E501
OpenAPI spec version: 1.1.0
Contact: hjelp@mailmojo.no
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import mailmojo_sdk
from mailmojo_sdk.api.page_api import PageApi # noqa: E501
from mailmojo_sdk.rest import ApiException
class TestPageApi(unittest.TestCase):
"""PageApi unit test stubs"""
def setUp(self):
self.api = mailmojo_sdk.api.page_api.PageApi() # noqa: E501
def tearDown(self):
pass
def test_get_page_by_id(self):
"""Test case for get_page_by_id
Retrieve a landing page. # noqa: E501
"""
pass
def test_get_pages(self):
"""Test case for get_pages
Retrieve all landing pages. # noqa: E501
"""
pass
def | (self):
"""Test case for update_page
Update a landing page partially. # noqa: E501
"""
pass
if __name__ == '__main__':
unittest.main()
| test_update_page | identifier_name |
test_page_api.py | # coding: utf-8
"""
MailMojo API
v1 of the MailMojo API # noqa: E501
OpenAPI spec version: 1.1.0
Contact: hjelp@mailmojo.no
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import mailmojo_sdk
from mailmojo_sdk.api.page_api import PageApi # noqa: E501
from mailmojo_sdk.rest import ApiException
class TestPageApi(unittest.TestCase):
"""PageApi unit test stubs"""
def setUp(self):
self.api = mailmojo_sdk.api.page_api.PageApi() # noqa: E501
def tearDown(self):
pass
def test_get_page_by_id(self):
"""Test case for get_page_by_id
Retrieve a landing page. # noqa: E501
"""
pass
def test_get_pages(self):
"""Test case for get_pages
Retrieve all landing pages. # noqa: E501
"""
pass
| Update a landing page partially. # noqa: E501
"""
pass
if __name__ == '__main__':
unittest.main() | def test_update_page(self):
"""Test case for update_page
| random_line_split |
test_page_api.py | # coding: utf-8
"""
MailMojo API
v1 of the MailMojo API # noqa: E501
OpenAPI spec version: 1.1.0
Contact: hjelp@mailmojo.no
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import mailmojo_sdk
from mailmojo_sdk.api.page_api import PageApi # noqa: E501
from mailmojo_sdk.rest import ApiException
class TestPageApi(unittest.TestCase):
|
if __name__ == '__main__':
unittest.main()
| """PageApi unit test stubs"""
def setUp(self):
self.api = mailmojo_sdk.api.page_api.PageApi() # noqa: E501
def tearDown(self):
pass
def test_get_page_by_id(self):
"""Test case for get_page_by_id
Retrieve a landing page. # noqa: E501
"""
pass
def test_get_pages(self):
"""Test case for get_pages
Retrieve all landing pages. # noqa: E501
"""
pass
def test_update_page(self):
"""Test case for update_page
Update a landing page partially. # noqa: E501
"""
pass | identifier_body |
test_page_api.py | # coding: utf-8
"""
MailMojo API
v1 of the MailMojo API # noqa: E501
OpenAPI spec version: 1.1.0
Contact: hjelp@mailmojo.no
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import mailmojo_sdk
from mailmojo_sdk.api.page_api import PageApi # noqa: E501
from mailmojo_sdk.rest import ApiException
class TestPageApi(unittest.TestCase):
"""PageApi unit test stubs"""
def setUp(self):
self.api = mailmojo_sdk.api.page_api.PageApi() # noqa: E501
def tearDown(self):
pass
def test_get_page_by_id(self):
"""Test case for get_page_by_id
Retrieve a landing page. # noqa: E501
"""
pass
def test_get_pages(self):
"""Test case for get_pages
Retrieve all landing pages. # noqa: E501
"""
pass
def test_update_page(self):
"""Test case for update_page
Update a landing page partially. # noqa: E501
"""
pass
if __name__ == '__main__':
| unittest.main() | conditional_block | |
gulpfile.js | const gulp = require('gulp');
const browserify = require('browserify');
const babelify = require('babelify');
const source = require('vinyl-source-stream');
const watchify = require('watchify');
const webserver = require('gulp-webserver');
const uglify = require('gulp-uglify');
const rename = require('gulp-rename');
const msx = require('gulp-msx');
const br = watchify(
browserify({
entries: './src/Solufa.ts'
})
.plugin('tsify', {target: 'es6'})
.transform("babelify")
);
br.on( "update", bundle );
function | () {
return br.bundle()
.pipe(source('Solufa.js'))
.pipe(gulp.dest('./static/js'));
}
gulp.task( "msx", function() {
gulp.src('./components/*.js')
.pipe(msx({harmony: true}))
.pipe(gulp.dest('./static/components'));
});
gulp.task( "default", function() {
gulp.src('./static')
.pipe(webserver({
host: '0.0.0.0',//スマホからIPアドレスでアクセスできる
livereload: true,
open: "http://0.0.0.0:8000/samples/1000box.html"
}));
bundle();
gulp.watch('./components/*.js', ['msx']);
});
gulp.task('compress', function() {
return gulp.src('static/js/Solufa.js')
.pipe(uglify({
preserveComments: 'some' // ! から始まるコメントを残すオプションを追加
}))
.pipe(rename('Solufa.min.js'))
.pipe(gulp.dest('static/js'));
});
| bundle | identifier_name |
gulpfile.js | const gulp = require('gulp');
const browserify = require('browserify');
const babelify = require('babelify');
const source = require('vinyl-source-stream');
const watchify = require('watchify');
const webserver = require('gulp-webserver');
const uglify = require('gulp-uglify'); | const br = watchify(
browserify({
entries: './src/Solufa.ts'
})
.plugin('tsify', {target: 'es6'})
.transform("babelify")
);
br.on( "update", bundle );
function bundle() {
return br.bundle()
.pipe(source('Solufa.js'))
.pipe(gulp.dest('./static/js'));
}
gulp.task( "msx", function() {
gulp.src('./components/*.js')
.pipe(msx({harmony: true}))
.pipe(gulp.dest('./static/components'));
});
gulp.task( "default", function() {
gulp.src('./static')
.pipe(webserver({
host: '0.0.0.0',//スマホからIPアドレスでアクセスできる
livereload: true,
open: "http://0.0.0.0:8000/samples/1000box.html"
}));
bundle();
gulp.watch('./components/*.js', ['msx']);
});
gulp.task('compress', function() {
return gulp.src('static/js/Solufa.js')
.pipe(uglify({
preserveComments: 'some' // ! から始まるコメントを残すオプションを追加
}))
.pipe(rename('Solufa.min.js'))
.pipe(gulp.dest('static/js'));
}); | const rename = require('gulp-rename');
const msx = require('gulp-msx');
| random_line_split |
gulpfile.js | const gulp = require('gulp');
const browserify = require('browserify');
const babelify = require('babelify');
const source = require('vinyl-source-stream');
const watchify = require('watchify');
const webserver = require('gulp-webserver');
const uglify = require('gulp-uglify');
const rename = require('gulp-rename');
const msx = require('gulp-msx');
const br = watchify(
browserify({
entries: './src/Solufa.ts'
})
.plugin('tsify', {target: 'es6'})
.transform("babelify")
);
br.on( "update", bundle );
function bundle() |
gulp.task( "msx", function() {
gulp.src('./components/*.js')
.pipe(msx({harmony: true}))
.pipe(gulp.dest('./static/components'));
});
gulp.task( "default", function() {
gulp.src('./static')
.pipe(webserver({
host: '0.0.0.0',//スマホからIPアドレスでアクセスできる
livereload: true,
open: "http://0.0.0.0:8000/samples/1000box.html"
}));
bundle();
gulp.watch('./components/*.js', ['msx']);
});
gulp.task('compress', function() {
return gulp.src('static/js/Solufa.js')
.pipe(uglify({
preserveComments: 'some' // ! から始まるコメントを残すオプションを追加
}))
.pipe(rename('Solufa.min.js'))
.pipe(gulp.dest('static/js'));
});
| {
return br.bundle()
.pipe(source('Solufa.js'))
.pipe(gulp.dest('./static/js'));
} | identifier_body |
try_chan.rs | // Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! A simple test program for evaluating the speed of cross-thread communications.
extern crate xi_rpc;
use std::thread;
use std::sync::mpsc;
/*
use xi_rpc::chan::Chan;
pub fn test_chan() {
let n_iter = 1000000;
let chan1 = Chan::new();
let chan1s = chan1.clone();
let chan2 = Chan::new();
let chan2s = chan2.clone();
let thread1 = thread::spawn(move|| {
for _ in 0..n_iter {
chan2s.try_send(chan1.recv());
}
});
let thread2 = thread::spawn(move|| {
for _ in 0..n_iter {
chan1s.try_send(42);
let _ = chan2.recv();
}
});
let _ = thread1.join();
let _ = thread2.join();
}
*/
pub fn test_mpsc() {
let n_iter = 1000000;
let (chan1s, chan1) = mpsc::channel();
let (chan2s, chan2) = mpsc::channel();
let thread1 = thread::spawn(move|| {
for _ in 0..n_iter {
chan2s.send(chan1.recv()).unwrap();
}
});
let thread2 = thread::spawn(move|| {
for _ in 0..n_iter {
chan1s.send(42).unwrap();
let _ = chan2.recv();
}
});
let _ = thread1.join();
let _ = thread2.join();
}
pub fn main() | {
test_mpsc()
} | identifier_body | |
try_chan.rs | // Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! A simple test program for evaluating the speed of cross-thread communications.
extern crate xi_rpc; | /*
use xi_rpc::chan::Chan;
pub fn test_chan() {
let n_iter = 1000000;
let chan1 = Chan::new();
let chan1s = chan1.clone();
let chan2 = Chan::new();
let chan2s = chan2.clone();
let thread1 = thread::spawn(move|| {
for _ in 0..n_iter {
chan2s.try_send(chan1.recv());
}
});
let thread2 = thread::spawn(move|| {
for _ in 0..n_iter {
chan1s.try_send(42);
let _ = chan2.recv();
}
});
let _ = thread1.join();
let _ = thread2.join();
}
*/
pub fn test_mpsc() {
let n_iter = 1000000;
let (chan1s, chan1) = mpsc::channel();
let (chan2s, chan2) = mpsc::channel();
let thread1 = thread::spawn(move|| {
for _ in 0..n_iter {
chan2s.send(chan1.recv()).unwrap();
}
});
let thread2 = thread::spawn(move|| {
for _ in 0..n_iter {
chan1s.send(42).unwrap();
let _ = chan2.recv();
}
});
let _ = thread1.join();
let _ = thread2.join();
}
pub fn main() {
test_mpsc()
} |
use std::thread;
use std::sync::mpsc;
| random_line_split |
try_chan.rs | // Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! A simple test program for evaluating the speed of cross-thread communications.
extern crate xi_rpc;
use std::thread;
use std::sync::mpsc;
/*
use xi_rpc::chan::Chan;
pub fn test_chan() {
let n_iter = 1000000;
let chan1 = Chan::new();
let chan1s = chan1.clone();
let chan2 = Chan::new();
let chan2s = chan2.clone();
let thread1 = thread::spawn(move|| {
for _ in 0..n_iter {
chan2s.try_send(chan1.recv());
}
});
let thread2 = thread::spawn(move|| {
for _ in 0..n_iter {
chan1s.try_send(42);
let _ = chan2.recv();
}
});
let _ = thread1.join();
let _ = thread2.join();
}
*/
pub fn | () {
let n_iter = 1000000;
let (chan1s, chan1) = mpsc::channel();
let (chan2s, chan2) = mpsc::channel();
let thread1 = thread::spawn(move|| {
for _ in 0..n_iter {
chan2s.send(chan1.recv()).unwrap();
}
});
let thread2 = thread::spawn(move|| {
for _ in 0..n_iter {
chan1s.send(42).unwrap();
let _ = chan2.recv();
}
});
let _ = thread1.join();
let _ = thread2.join();
}
pub fn main() {
test_mpsc()
}
| test_mpsc | identifier_name |
get_type_id.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::any::Any;
use core::any::TypeId;
// #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
// #[stable(feature = "rust1", since = "1.0.0")]
// pub struct TypeId {
// t: u64,
// }
// impl<T: Reflect + 'static> Any for T {
// fn get_type_id(&self) -> TypeId { TypeId::of::<T>() }
// }
type T = i32;
#[test]
fn get_type_id_test1() {
let x: T = 68;
let y: T = 500;
let x_typeid: TypeId = x.get_type_id();
let y_typeid: TypeId = y.get_type_id();
assert_eq!(x_typeid, y_typeid);
}
#[test]
fn get_type_id_test2() |
}
| {
struct A;
let x: A = A;
let _: TypeId = x.get_type_id();
} | identifier_body |
get_type_id.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::any::Any;
use core::any::TypeId;
// #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
// #[stable(feature = "rust1", since = "1.0.0")]
// pub struct TypeId {
// t: u64,
// }
// impl<T: Reflect + 'static> Any for T {
// fn get_type_id(&self) -> TypeId { TypeId::of::<T>() }
// }
type T = i32;
#[test]
fn get_type_id_test1() {
let x: T = 68;
let y: T = 500;
let x_typeid: TypeId = x.get_type_id();
let y_typeid: TypeId = y.get_type_id();
assert_eq!(x_typeid, y_typeid);
}
#[test]
fn get_type_id_test2() {
struct A;
let x: A = A;
let _: TypeId = x.get_type_id(); | }
} | random_line_split | |
get_type_id.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::any::Any;
use core::any::TypeId;
// #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
// #[stable(feature = "rust1", since = "1.0.0")]
// pub struct TypeId {
// t: u64,
// }
// impl<T: Reflect + 'static> Any for T {
// fn get_type_id(&self) -> TypeId { TypeId::of::<T>() }
// }
type T = i32;
#[test]
fn get_type_id_test1() {
let x: T = 68;
let y: T = 500;
let x_typeid: TypeId = x.get_type_id();
let y_typeid: TypeId = y.get_type_id();
assert_eq!(x_typeid, y_typeid);
}
#[test]
fn get_type_id_test2() {
struct | ;
let x: A = A;
let _: TypeId = x.get_type_id();
}
}
| A | identifier_name |
Set.js | /*
Copyright 2008-2013 Clipperz Srl
This file is part of Clipperz, the online password manager.
For further information about its features and functionalities please
refer to http://www.clipperz.com.
* Clipperz is free software: you can redistribute it and/or modify it
under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
* Clipperz is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public
License along with Clipperz. If not, see http://www.gnu.org/licenses/.
*/
if (typeof(Clipperz) == 'undefined') {
Clipperz = {};
}
//#############################################################################
Clipperz.Set = function(args) {
args = args || {};
// MochiKit.Base.bindMethods(this);
if (args.items != null) {
this._items = args.items.slice();
} else {
this._items = [];
}
return this;
}
//=============================================================================
Clipperz.Set.prototype = MochiKit.Base.update(null, {
//-------------------------------------------------------------------------
'toString': function() {
return "Clipperz.Set";
},
//-------------------------------------------------------------------------
'items': function() {
return this._items;
},
//-------------------------------------------------------------------------
'popAnItem': function() {
var result;
if (this.size() > 0) {
result = this.items().pop();
} else {
result = null;
}
return result;
},
//-------------------------------------------------------------------------
'allItems': function() {
return this.items();
},
//-------------------------------------------------------------------------
'contains': function(anItem) {
return (this.indexOf(anItem) != -1);
},
//-------------------------------------------------------------------------
'indexOf': function(anItem) {
var result;
var i, c;
result = -1;
c = this.items().length;
for (i=0; (i<c) && (result == -1); i++) {
if (this.items()[i] === anItem) {
result = i;
}
}
return result;
},
//-------------------------------------------------------------------------
'add': function(anItem) {
if (anItem.constructor == Array) {
MochiKit.Base.map(MochiKit.Base.bind(this,add, this), anItem);
} else |
},
//-------------------------------------------------------------------------
'debug': function() {
var i, c;
result = -1;
c = this.items().length;
for (i=0; i<c; i++) {
alert("[" + i + "] " + this.items()[i].label);
}
},
//-------------------------------------------------------------------------
'remove': function(anItem) {
if (anItem.constructor == Array) {
MochiKit.Base.map(MochiKit.Base.bind(this.remove, this), anItem);
} else {
var itemIndex;
itemIndex = this.indexOf(anItem);
if (itemIndex != -1) {
this.items().splice(itemIndex, 1);
}
}
},
//-------------------------------------------------------------------------
'size': function() {
return this.items().length;
},
//-------------------------------------------------------------------------
'empty': function() {
this.items().splice(0, this.items().length);
},
//-------------------------------------------------------------------------
__syntaxFix__: "syntax fix"
//-------------------------------------------------------------------------
});
| {
if (! this.contains(anItem)) {
this.items().push(anItem);
}
} | conditional_block |
Set.js | /*
Copyright 2008-2013 Clipperz Srl
This file is part of Clipperz, the online password manager.
For further information about its features and functionalities please
refer to http://www.clipperz.com.
* Clipperz is free software: you can redistribute it and/or modify it
under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
* Clipperz is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public
License along with Clipperz. If not, see http://www.gnu.org/licenses/.
*/
if (typeof(Clipperz) == 'undefined') {
Clipperz = {};
}
//#############################################################################
Clipperz.Set = function(args) {
args = args || {};
// MochiKit.Base.bindMethods(this);
if (args.items != null) {
this._items = args.items.slice();
} else {
this._items = [];
}
return this;
}
//=============================================================================
Clipperz.Set.prototype = MochiKit.Base.update(null, {
//-------------------------------------------------------------------------
| 'toString': function() {
return "Clipperz.Set";
},
//-------------------------------------------------------------------------
'items': function() {
return this._items;
},
//-------------------------------------------------------------------------
'popAnItem': function() {
var result;
if (this.size() > 0) {
result = this.items().pop();
} else {
result = null;
}
return result;
},
//-------------------------------------------------------------------------
'allItems': function() {
return this.items();
},
//-------------------------------------------------------------------------
'contains': function(anItem) {
return (this.indexOf(anItem) != -1);
},
//-------------------------------------------------------------------------
'indexOf': function(anItem) {
var result;
var i, c;
result = -1;
c = this.items().length;
for (i=0; (i<c) && (result == -1); i++) {
if (this.items()[i] === anItem) {
result = i;
}
}
return result;
},
//-------------------------------------------------------------------------
'add': function(anItem) {
if (anItem.constructor == Array) {
MochiKit.Base.map(MochiKit.Base.bind(this,add, this), anItem);
} else {
if (! this.contains(anItem)) {
this.items().push(anItem);
}
}
},
//-------------------------------------------------------------------------
'debug': function() {
var i, c;
result = -1;
c = this.items().length;
for (i=0; i<c; i++) {
alert("[" + i + "] " + this.items()[i].label);
}
},
//-------------------------------------------------------------------------
'remove': function(anItem) {
if (anItem.constructor == Array) {
MochiKit.Base.map(MochiKit.Base.bind(this.remove, this), anItem);
} else {
var itemIndex;
itemIndex = this.indexOf(anItem);
if (itemIndex != -1) {
this.items().splice(itemIndex, 1);
}
}
},
//-------------------------------------------------------------------------
'size': function() {
return this.items().length;
},
//-------------------------------------------------------------------------
'empty': function() {
this.items().splice(0, this.items().length);
},
//-------------------------------------------------------------------------
__syntaxFix__: "syntax fix"
//-------------------------------------------------------------------------
}); | random_line_split | |
deploy_base.py | """
Deployment for Bedrock in production.
Requires commander (https://github.com/oremj/commander) which is installed on
the systems that need it.
"""
import os
import random
import re
import urllib
import urllib2
from commander.deploy import commands, task, hostgroups
import commander_settings as settings
NEW_RELIC_API_KEY = getattr(settings, 'NEW_RELIC_API_KEY', None)
NEW_RELIC_APP_ID = getattr(settings, 'NEW_RELIC_APP_ID', None)
NEW_RELIC_URL = 'https://rpm.newrelic.com/deployments.xml'
GITHUB_URL = 'https://github.com/mozilla/bedrock/compare/{oldrev}...{newrev}'
def management_cmd(ctx, cmd):
"""Run a Django management command correctly."""
with ctx.lcd(settings.SRC_DIR):
ctx.local('LANG=en_US.UTF-8 python2.6 manage.py ' + cmd)
@task
def reload_crond(ctx):
ctx.local("killall -SIGHUP crond")
@task
def update_code(ctx, tag):
with ctx.lcd(settings.SRC_DIR):
ctx.local("git fetch --all")
ctx.local("git checkout -f %s" % tag)
ctx.local("git submodule sync")
ctx.local("git submodule update --init --recursive")
@task
def update_locales(ctx):
with ctx.lcd(os.path.join(settings.SRC_DIR, 'locale')):
ctx.local("svn up")
@task
def update_assets(ctx):
management_cmd(ctx, 'compress_assets')
management_cmd(ctx, 'update_product_details')
management_cmd(ctx, 'update_externalfiles')
@task
def update_revision_file(ctx):
with ctx.lcd(settings.SRC_DIR):
ctx.local("mv media/revision.txt media/prev-revision.txt")
ctx.local("git rev-parse HEAD > media/revision.txt")
@task
def database(ctx):
management_cmd(ctx, 'syncdb --migrate --noinput')
@task
def checkin_changes(ctx):
ctx.local(settings.DEPLOY_SCRIPT)
@hostgroups(settings.WEB_HOSTGROUP, remote_kwargs={'ssh_key': settings.SSH_KEY})
def deploy_app(ctx):
ctx.remote(settings.REMOTE_UPDATE_SCRIPT)
# ctx.remote("/bin/touch %s" % settings.REMOTE_WSGI)
ctx.remote("service httpd graceful")
@task
def update_info(ctx):
with ctx.lcd(settings.SRC_DIR):
ctx.local("date")
ctx.local("git branch")
ctx.local("git log -3")
ctx.local("git status")
ctx.local("git submodule status")
with ctx.lcd("locale"):
ctx.local("svn info")
ctx.local("svn status")
management_cmd(ctx, 'migrate --list')
@task
def ping_newrelic(ctx):
if NEW_RELIC_API_KEY and NEW_RELIC_APP_ID:
with ctx.lcd(settings.SRC_DIR):
oldrev = ctx.local('cat media/prev-revision.txt').out.strip()
newrev = ctx.local('cat media/revision.txt').out.strip() | desc = generate_desc(oldrev, newrev, changelog)
if changelog:
github_url = GITHUB_URL.format(oldrev=oldrev, newrev=newrev)
changelog = '{0}\n\n{1}'.format(changelog, github_url)
data = urllib.urlencode({
'deployment[description]': desc,
'deployment[revision]': newrev,
'deployment[app_id]': NEW_RELIC_APP_ID,
'deployment[changelog]': changelog,
})
headers = {'x-api-key': NEW_RELIC_API_KEY}
try:
request = urllib2.Request(NEW_RELIC_URL, data, headers)
urllib2.urlopen(request)
except urllib.URLError as exp:
print 'Error notifying New Relic: {0}'.format(exp)
@task
def pre_update(ctx, ref=settings.UPDATE_REF):
commands['update_code'](ref)
commands['update_info']()
@task
def update(ctx):
commands['database']()
commands['update_assets']()
commands['update_locales']()
commands['update_revision_file']()
commands['reload_crond']()
@task
def deploy(ctx):
commands['checkin_changes']()
commands['deploy_app']()
commands['ping_newrelic']()
@task
def update_bedrock(ctx, tag):
"""Do typical bedrock update"""
commands['pre_update'](tag)
commands['update']()
# utility functions #
# shamelessly stolen from https://github.com/mythmon/chief-james/
def get_random_desc():
return random.choice([
'No bugfixes--must be adding infinite loops.',
'No bugfixes--must be rot13ing function names for code security.',
'No bugfixes--must be demonstrating our elite push technology.',
'No bugfixes--must be testing james.',
])
def extract_bugs(changelog):
"""Takes output from git log --oneline and extracts bug numbers"""
bug_regexp = re.compile(r'\bbug (\d+)\b', re.I)
bugs = set()
for line in changelog:
for bug in bug_regexp.findall(line):
bugs.add(bug)
return sorted(list(bugs))
def generate_desc(from_commit, to_commit, changelog):
"""Figures out a good description based on what we're pushing out."""
if from_commit.startswith(to_commit):
desc = 'Pushing {0} again'.format(to_commit)
else:
bugs = extract_bugs(changelog.split('\n'))
if bugs:
bugs = ['bug #{0}'.format(bug) for bug in bugs]
desc = 'Fixing: {0}'.format(', '.join(bugs))
else:
desc = get_random_desc()
return desc | log_cmd = 'git log --oneline {0}..{1}'.format(oldrev, newrev)
changelog = ctx.local(log_cmd).out.strip()
print 'Post deployment to New Relic' | random_line_split |
deploy_base.py | """
Deployment for Bedrock in production.
Requires commander (https://github.com/oremj/commander) which is installed on
the systems that need it.
"""
import os
import random
import re
import urllib
import urllib2
from commander.deploy import commands, task, hostgroups
import commander_settings as settings
NEW_RELIC_API_KEY = getattr(settings, 'NEW_RELIC_API_KEY', None)
NEW_RELIC_APP_ID = getattr(settings, 'NEW_RELIC_APP_ID', None)
NEW_RELIC_URL = 'https://rpm.newrelic.com/deployments.xml'
GITHUB_URL = 'https://github.com/mozilla/bedrock/compare/{oldrev}...{newrev}'
def management_cmd(ctx, cmd):
"""Run a Django management command correctly."""
with ctx.lcd(settings.SRC_DIR):
ctx.local('LANG=en_US.UTF-8 python2.6 manage.py ' + cmd)
@task
def reload_crond(ctx):
ctx.local("killall -SIGHUP crond")
@task
def update_code(ctx, tag):
with ctx.lcd(settings.SRC_DIR):
ctx.local("git fetch --all")
ctx.local("git checkout -f %s" % tag)
ctx.local("git submodule sync")
ctx.local("git submodule update --init --recursive")
@task
def update_locales(ctx):
with ctx.lcd(os.path.join(settings.SRC_DIR, 'locale')):
ctx.local("svn up")
@task
def update_assets(ctx):
management_cmd(ctx, 'compress_assets')
management_cmd(ctx, 'update_product_details')
management_cmd(ctx, 'update_externalfiles')
@task
def update_revision_file(ctx):
with ctx.lcd(settings.SRC_DIR):
ctx.local("mv media/revision.txt media/prev-revision.txt")
ctx.local("git rev-parse HEAD > media/revision.txt")
@task
def database(ctx):
management_cmd(ctx, 'syncdb --migrate --noinput')
@task
def checkin_changes(ctx):
ctx.local(settings.DEPLOY_SCRIPT)
@hostgroups(settings.WEB_HOSTGROUP, remote_kwargs={'ssh_key': settings.SSH_KEY})
def deploy_app(ctx):
ctx.remote(settings.REMOTE_UPDATE_SCRIPT)
# ctx.remote("/bin/touch %s" % settings.REMOTE_WSGI)
ctx.remote("service httpd graceful")
@task
def update_info(ctx):
with ctx.lcd(settings.SRC_DIR):
ctx.local("date")
ctx.local("git branch")
ctx.local("git log -3")
ctx.local("git status")
ctx.local("git submodule status")
with ctx.lcd("locale"):
ctx.local("svn info")
ctx.local("svn status")
management_cmd(ctx, 'migrate --list')
@task
def ping_newrelic(ctx):
|
@task
def pre_update(ctx, ref=settings.UPDATE_REF):
commands['update_code'](ref)
commands['update_info']()
@task
def update(ctx):
commands['database']()
commands['update_assets']()
commands['update_locales']()
commands['update_revision_file']()
commands['reload_crond']()
@task
def deploy(ctx):
commands['checkin_changes']()
commands['deploy_app']()
commands['ping_newrelic']()
@task
def update_bedrock(ctx, tag):
"""Do typical bedrock update"""
commands['pre_update'](tag)
commands['update']()
# utility functions #
# shamelessly stolen from https://github.com/mythmon/chief-james/
def get_random_desc():
return random.choice([
'No bugfixes--must be adding infinite loops.',
'No bugfixes--must be rot13ing function names for code security.',
'No bugfixes--must be demonstrating our elite push technology.',
'No bugfixes--must be testing james.',
])
def extract_bugs(changelog):
"""Takes output from git log --oneline and extracts bug numbers"""
bug_regexp = re.compile(r'\bbug (\d+)\b', re.I)
bugs = set()
for line in changelog:
for bug in bug_regexp.findall(line):
bugs.add(bug)
return sorted(list(bugs))
def generate_desc(from_commit, to_commit, changelog):
"""Figures out a good description based on what we're pushing out."""
if from_commit.startswith(to_commit):
desc = 'Pushing {0} again'.format(to_commit)
else:
bugs = extract_bugs(changelog.split('\n'))
if bugs:
bugs = ['bug #{0}'.format(bug) for bug in bugs]
desc = 'Fixing: {0}'.format(', '.join(bugs))
else:
desc = get_random_desc()
return desc
| if NEW_RELIC_API_KEY and NEW_RELIC_APP_ID:
with ctx.lcd(settings.SRC_DIR):
oldrev = ctx.local('cat media/prev-revision.txt').out.strip()
newrev = ctx.local('cat media/revision.txt').out.strip()
log_cmd = 'git log --oneline {0}..{1}'.format(oldrev, newrev)
changelog = ctx.local(log_cmd).out.strip()
print 'Post deployment to New Relic'
desc = generate_desc(oldrev, newrev, changelog)
if changelog:
github_url = GITHUB_URL.format(oldrev=oldrev, newrev=newrev)
changelog = '{0}\n\n{1}'.format(changelog, github_url)
data = urllib.urlencode({
'deployment[description]': desc,
'deployment[revision]': newrev,
'deployment[app_id]': NEW_RELIC_APP_ID,
'deployment[changelog]': changelog,
})
headers = {'x-api-key': NEW_RELIC_API_KEY}
try:
request = urllib2.Request(NEW_RELIC_URL, data, headers)
urllib2.urlopen(request)
except urllib.URLError as exp:
print 'Error notifying New Relic: {0}'.format(exp) | identifier_body |
deploy_base.py | """
Deployment for Bedrock in production.
Requires commander (https://github.com/oremj/commander) which is installed on
the systems that need it.
"""
import os
import random
import re
import urllib
import urllib2
from commander.deploy import commands, task, hostgroups
import commander_settings as settings
NEW_RELIC_API_KEY = getattr(settings, 'NEW_RELIC_API_KEY', None)
NEW_RELIC_APP_ID = getattr(settings, 'NEW_RELIC_APP_ID', None)
NEW_RELIC_URL = 'https://rpm.newrelic.com/deployments.xml'
GITHUB_URL = 'https://github.com/mozilla/bedrock/compare/{oldrev}...{newrev}'
def management_cmd(ctx, cmd):
"""Run a Django management command correctly."""
with ctx.lcd(settings.SRC_DIR):
ctx.local('LANG=en_US.UTF-8 python2.6 manage.py ' + cmd)
@task
def reload_crond(ctx):
ctx.local("killall -SIGHUP crond")
@task
def update_code(ctx, tag):
with ctx.lcd(settings.SRC_DIR):
ctx.local("git fetch --all")
ctx.local("git checkout -f %s" % tag)
ctx.local("git submodule sync")
ctx.local("git submodule update --init --recursive")
@task
def update_locales(ctx):
with ctx.lcd(os.path.join(settings.SRC_DIR, 'locale')):
ctx.local("svn up")
@task
def update_assets(ctx):
management_cmd(ctx, 'compress_assets')
management_cmd(ctx, 'update_product_details')
management_cmd(ctx, 'update_externalfiles')
@task
def update_revision_file(ctx):
with ctx.lcd(settings.SRC_DIR):
ctx.local("mv media/revision.txt media/prev-revision.txt")
ctx.local("git rev-parse HEAD > media/revision.txt")
@task
def database(ctx):
management_cmd(ctx, 'syncdb --migrate --noinput')
@task
def checkin_changes(ctx):
ctx.local(settings.DEPLOY_SCRIPT)
@hostgroups(settings.WEB_HOSTGROUP, remote_kwargs={'ssh_key': settings.SSH_KEY})
def deploy_app(ctx):
ctx.remote(settings.REMOTE_UPDATE_SCRIPT)
# ctx.remote("/bin/touch %s" % settings.REMOTE_WSGI)
ctx.remote("service httpd graceful")
@task
def update_info(ctx):
with ctx.lcd(settings.SRC_DIR):
ctx.local("date")
ctx.local("git branch")
ctx.local("git log -3")
ctx.local("git status")
ctx.local("git submodule status")
with ctx.lcd("locale"):
ctx.local("svn info")
ctx.local("svn status")
management_cmd(ctx, 'migrate --list')
@task
def ping_newrelic(ctx):
if NEW_RELIC_API_KEY and NEW_RELIC_APP_ID:
with ctx.lcd(settings.SRC_DIR):
oldrev = ctx.local('cat media/prev-revision.txt').out.strip()
newrev = ctx.local('cat media/revision.txt').out.strip()
log_cmd = 'git log --oneline {0}..{1}'.format(oldrev, newrev)
changelog = ctx.local(log_cmd).out.strip()
print 'Post deployment to New Relic'
desc = generate_desc(oldrev, newrev, changelog)
if changelog:
github_url = GITHUB_URL.format(oldrev=oldrev, newrev=newrev)
changelog = '{0}\n\n{1}'.format(changelog, github_url)
data = urllib.urlencode({
'deployment[description]': desc,
'deployment[revision]': newrev,
'deployment[app_id]': NEW_RELIC_APP_ID,
'deployment[changelog]': changelog,
})
headers = {'x-api-key': NEW_RELIC_API_KEY}
try:
request = urllib2.Request(NEW_RELIC_URL, data, headers)
urllib2.urlopen(request)
except urllib.URLError as exp:
print 'Error notifying New Relic: {0}'.format(exp)
@task
def pre_update(ctx, ref=settings.UPDATE_REF):
commands['update_code'](ref)
commands['update_info']()
@task
def update(ctx):
commands['database']()
commands['update_assets']()
commands['update_locales']()
commands['update_revision_file']()
commands['reload_crond']()
@task
def deploy(ctx):
commands['checkin_changes']()
commands['deploy_app']()
commands['ping_newrelic']()
@task
def update_bedrock(ctx, tag):
"""Do typical bedrock update"""
commands['pre_update'](tag)
commands['update']()
# utility functions #
# shamelessly stolen from https://github.com/mythmon/chief-james/
def get_random_desc():
return random.choice([
'No bugfixes--must be adding infinite loops.',
'No bugfixes--must be rot13ing function names for code security.',
'No bugfixes--must be demonstrating our elite push technology.',
'No bugfixes--must be testing james.',
])
def extract_bugs(changelog):
"""Takes output from git log --oneline and extracts bug numbers"""
bug_regexp = re.compile(r'\bbug (\d+)\b', re.I)
bugs = set()
for line in changelog:
for bug in bug_regexp.findall(line):
|
return sorted(list(bugs))
def generate_desc(from_commit, to_commit, changelog):
"""Figures out a good description based on what we're pushing out."""
if from_commit.startswith(to_commit):
desc = 'Pushing {0} again'.format(to_commit)
else:
bugs = extract_bugs(changelog.split('\n'))
if bugs:
bugs = ['bug #{0}'.format(bug) for bug in bugs]
desc = 'Fixing: {0}'.format(', '.join(bugs))
else:
desc = get_random_desc()
return desc
| bugs.add(bug) | conditional_block |
deploy_base.py | """
Deployment for Bedrock in production.
Requires commander (https://github.com/oremj/commander) which is installed on
the systems that need it.
"""
import os
import random
import re
import urllib
import urllib2
from commander.deploy import commands, task, hostgroups
import commander_settings as settings
NEW_RELIC_API_KEY = getattr(settings, 'NEW_RELIC_API_KEY', None)
NEW_RELIC_APP_ID = getattr(settings, 'NEW_RELIC_APP_ID', None)
NEW_RELIC_URL = 'https://rpm.newrelic.com/deployments.xml'
GITHUB_URL = 'https://github.com/mozilla/bedrock/compare/{oldrev}...{newrev}'
def management_cmd(ctx, cmd):
"""Run a Django management command correctly."""
with ctx.lcd(settings.SRC_DIR):
ctx.local('LANG=en_US.UTF-8 python2.6 manage.py ' + cmd)
@task
def reload_crond(ctx):
ctx.local("killall -SIGHUP crond")
@task
def | (ctx, tag):
with ctx.lcd(settings.SRC_DIR):
ctx.local("git fetch --all")
ctx.local("git checkout -f %s" % tag)
ctx.local("git submodule sync")
ctx.local("git submodule update --init --recursive")
@task
def update_locales(ctx):
with ctx.lcd(os.path.join(settings.SRC_DIR, 'locale')):
ctx.local("svn up")
@task
def update_assets(ctx):
management_cmd(ctx, 'compress_assets')
management_cmd(ctx, 'update_product_details')
management_cmd(ctx, 'update_externalfiles')
@task
def update_revision_file(ctx):
with ctx.lcd(settings.SRC_DIR):
ctx.local("mv media/revision.txt media/prev-revision.txt")
ctx.local("git rev-parse HEAD > media/revision.txt")
@task
def database(ctx):
management_cmd(ctx, 'syncdb --migrate --noinput')
@task
def checkin_changes(ctx):
ctx.local(settings.DEPLOY_SCRIPT)
@hostgroups(settings.WEB_HOSTGROUP, remote_kwargs={'ssh_key': settings.SSH_KEY})
def deploy_app(ctx):
ctx.remote(settings.REMOTE_UPDATE_SCRIPT)
# ctx.remote("/bin/touch %s" % settings.REMOTE_WSGI)
ctx.remote("service httpd graceful")
@task
def update_info(ctx):
with ctx.lcd(settings.SRC_DIR):
ctx.local("date")
ctx.local("git branch")
ctx.local("git log -3")
ctx.local("git status")
ctx.local("git submodule status")
with ctx.lcd("locale"):
ctx.local("svn info")
ctx.local("svn status")
management_cmd(ctx, 'migrate --list')
@task
def ping_newrelic(ctx):
if NEW_RELIC_API_KEY and NEW_RELIC_APP_ID:
with ctx.lcd(settings.SRC_DIR):
oldrev = ctx.local('cat media/prev-revision.txt').out.strip()
newrev = ctx.local('cat media/revision.txt').out.strip()
log_cmd = 'git log --oneline {0}..{1}'.format(oldrev, newrev)
changelog = ctx.local(log_cmd).out.strip()
print 'Post deployment to New Relic'
desc = generate_desc(oldrev, newrev, changelog)
if changelog:
github_url = GITHUB_URL.format(oldrev=oldrev, newrev=newrev)
changelog = '{0}\n\n{1}'.format(changelog, github_url)
data = urllib.urlencode({
'deployment[description]': desc,
'deployment[revision]': newrev,
'deployment[app_id]': NEW_RELIC_APP_ID,
'deployment[changelog]': changelog,
})
headers = {'x-api-key': NEW_RELIC_API_KEY}
try:
request = urllib2.Request(NEW_RELIC_URL, data, headers)
urllib2.urlopen(request)
except urllib.URLError as exp:
print 'Error notifying New Relic: {0}'.format(exp)
@task
def pre_update(ctx, ref=settings.UPDATE_REF):
commands['update_code'](ref)
commands['update_info']()
@task
def update(ctx):
commands['database']()
commands['update_assets']()
commands['update_locales']()
commands['update_revision_file']()
commands['reload_crond']()
@task
def deploy(ctx):
commands['checkin_changes']()
commands['deploy_app']()
commands['ping_newrelic']()
@task
def update_bedrock(ctx, tag):
"""Do typical bedrock update"""
commands['pre_update'](tag)
commands['update']()
# utility functions #
# shamelessly stolen from https://github.com/mythmon/chief-james/
def get_random_desc():
return random.choice([
'No bugfixes--must be adding infinite loops.',
'No bugfixes--must be rot13ing function names for code security.',
'No bugfixes--must be demonstrating our elite push technology.',
'No bugfixes--must be testing james.',
])
def extract_bugs(changelog):
"""Takes output from git log --oneline and extracts bug numbers"""
bug_regexp = re.compile(r'\bbug (\d+)\b', re.I)
bugs = set()
for line in changelog:
for bug in bug_regexp.findall(line):
bugs.add(bug)
return sorted(list(bugs))
def generate_desc(from_commit, to_commit, changelog):
"""Figures out a good description based on what we're pushing out."""
if from_commit.startswith(to_commit):
desc = 'Pushing {0} again'.format(to_commit)
else:
bugs = extract_bugs(changelog.split('\n'))
if bugs:
bugs = ['bug #{0}'.format(bug) for bug in bugs]
desc = 'Fixing: {0}'.format(', '.join(bugs))
else:
desc = get_random_desc()
return desc
| update_code | identifier_name |
plugin.py | # -*- coding: iso-8859-1 -*-
# (c) 2006 Stephan Reichholf
# This Software is Free, use it where you want, when you want for whatever you want and modify it if you want but don't remove my copyright!
from Screens.Screen import Screen
from Screens.Standby import TryQuitMainloop
from Screens.MessageBox import MessageBox
from Components.ActionMap import NumberActionMap
from Components.Pixmap import Pixmap
from Components.Sources.StaticText import StaticText
from Components.MenuList import MenuList
from Plugins.Plugin import PluginDescriptor
from Components.config import config
from Tools.Directories import resolveFilename, SCOPE_PLUGINS
from enigma import eEnv
import os
SKINXML = "skin.xml"
DEFAULTSKIN = "<Default Skin>"
class SkinSelector(Screen):
# for i18n:
# _("Choose your Skin")
skinlist = []
root = os.path.join(eEnv.resolve("${datadir}"),"enigma2")
def __init__(self, session, args = None):
Screen.__init__(self, session)
self.skinlist = []
self.previewPath = ""
if os.path.exists(os.path.join(self.root, SKINXML)):
self.skinlist.append(DEFAULTSKIN)
for root, dirs, files in os.walk(self.root, followlinks=True):
for subdir in dirs:
dir = os.path.join(root,subdir)
if os.path.exists(os.path.join(dir,SKINXML)):
self.skinlist.append(subdir)
dirs = []
self["key_red"] = StaticText(_("Close"))
self["introduction"] = StaticText(_("Press OK to activate the selected skin."))
self.skinlist.sort()
self["SkinList"] = MenuList(self.skinlist)
self["Preview"] = Pixmap()
self["actions"] = NumberActionMap(["WizardActions", "InputActions", "EPGSelectActions"],
{
"ok": self.ok,
"back": self.close,
"red": self.close,
"up": self.up,
"down": self.down,
"left": self.left,
"right": self.right,
"info": self.info,
}, -1)
self.onLayoutFinish.append(self.layoutFinished)
def layoutFinished(self):
tmp = config.skin.primary_skin.value.find("/"+SKINXML)
if tmp != -1:
tmp = config.skin.primary_skin.value[:tmp]
idx = 0
for skin in self.skinlist:
if skin == tmp:
break
idx += 1
if idx < len(self.skinlist):
self["SkinList"].moveToIndex(idx)
self.loadPreview()
def up(self):
self["SkinList"].up()
self.loadPreview()
def | (self):
self["SkinList"].down()
self.loadPreview()
def left(self):
self["SkinList"].pageUp()
self.loadPreview()
def right(self):
self["SkinList"].pageDown()
self.loadPreview()
def info(self):
aboutbox = self.session.open(MessageBox,_("STB-GUI Skinselector\n\nIf you experience any problems please contact\nstephan@reichholf.net\n\n\xA9 2006 - Stephan Reichholf"), MessageBox.TYPE_INFO)
aboutbox.setTitle(_("About..."))
def ok(self):
if self["SkinList"].getCurrent() == DEFAULTSKIN:
self.skinfile = "."
else:
self.skinfile = self["SkinList"].getCurrent()
self.skinfile = os.path.join(self.skinfile, SKINXML)
print "Skinselector: Selected Skin: "+self.root+self.skinfile
restartbox = self.session.openWithCallback(self.restartGUI,MessageBox,_("GUI needs a restart to apply a new skin\nDo you want to restart the GUI now?"), MessageBox.TYPE_YESNO)
restartbox.setTitle(_("Restart GUI now?"))
def loadPreview(self):
if self["SkinList"].getCurrent() == DEFAULTSKIN:
pngpath = "."
else:
pngpath = self["SkinList"].getCurrent()
pngpath = os.path.join(os.path.join(self.root, pngpath), "prev.png")
if not os.path.exists(pngpath):
pngpath = resolveFilename(SCOPE_PLUGINS, "SystemPlugins/SkinSelector/noprev.png")
if self.previewPath != pngpath:
self.previewPath = pngpath
self["Preview"].instance.setPixmapFromFile(self.previewPath)
def restartGUI(self, answer):
if answer is True:
config.skin.primary_skin.value = self.skinfile
config.skin.primary_skin.save()
self.session.open(TryQuitMainloop, 3)
def SkinSelMain(session, **kwargs):
session.open(SkinSelector)
def SkinSelSetup(menuid, **kwargs):
if menuid == "ui_menu":
return [(_("Skin"), SkinSelMain, "skin_selector", None)]
else:
return []
def Plugins(**kwargs):
return PluginDescriptor(name="Skinselector", description="Select Your Skin", where = PluginDescriptor.WHERE_MENU, needsRestart = False, fnc=SkinSelSetup)
| down | identifier_name |
plugin.py | # -*- coding: iso-8859-1 -*-
# (c) 2006 Stephan Reichholf
# This Software is Free, use it where you want, when you want for whatever you want and modify it if you want but don't remove my copyright!
from Screens.Screen import Screen
from Screens.Standby import TryQuitMainloop
from Screens.MessageBox import MessageBox
from Components.ActionMap import NumberActionMap
from Components.Pixmap import Pixmap
from Components.Sources.StaticText import StaticText
from Components.MenuList import MenuList
from Plugins.Plugin import PluginDescriptor
from Components.config import config
from Tools.Directories import resolveFilename, SCOPE_PLUGINS
from enigma import eEnv
import os
SKINXML = "skin.xml"
DEFAULTSKIN = "<Default Skin>"
class SkinSelector(Screen):
# for i18n:
# _("Choose your Skin")
skinlist = []
root = os.path.join(eEnv.resolve("${datadir}"),"enigma2")
def __init__(self, session, args = None):
Screen.__init__(self, session)
self.skinlist = []
self.previewPath = ""
if os.path.exists(os.path.join(self.root, SKINXML)):
self.skinlist.append(DEFAULTSKIN)
for root, dirs, files in os.walk(self.root, followlinks=True):
for subdir in dirs:
dir = os.path.join(root,subdir)
if os.path.exists(os.path.join(dir,SKINXML)):
self.skinlist.append(subdir)
dirs = []
self["key_red"] = StaticText(_("Close"))
self["introduction"] = StaticText(_("Press OK to activate the selected skin."))
self.skinlist.sort()
self["SkinList"] = MenuList(self.skinlist)
self["Preview"] = Pixmap()
self["actions"] = NumberActionMap(["WizardActions", "InputActions", "EPGSelectActions"],
{
"ok": self.ok,
"back": self.close,
"red": self.close,
"up": self.up,
"down": self.down,
"left": self.left,
"right": self.right,
"info": self.info,
}, -1)
self.onLayoutFinish.append(self.layoutFinished)
def layoutFinished(self):
tmp = config.skin.primary_skin.value.find("/"+SKINXML)
if tmp != -1:
tmp = config.skin.primary_skin.value[:tmp]
idx = 0
for skin in self.skinlist:
if skin == tmp:
break
idx += 1
if idx < len(self.skinlist):
self["SkinList"].moveToIndex(idx)
self.loadPreview()
def up(self):
self["SkinList"].up()
self.loadPreview()
def down(self):
self["SkinList"].down()
self.loadPreview()
def left(self):
self["SkinList"].pageUp()
self.loadPreview()
def right(self):
self["SkinList"].pageDown()
self.loadPreview()
def info(self):
aboutbox = self.session.open(MessageBox,_("STB-GUI Skinselector\n\nIf you experience any problems please contact\nstephan@reichholf.net\n\n\xA9 2006 - Stephan Reichholf"), MessageBox.TYPE_INFO)
aboutbox.setTitle(_("About..."))
def ok(self):
if self["SkinList"].getCurrent() == DEFAULTSKIN:
self.skinfile = "."
else:
|
self.skinfile = os.path.join(self.skinfile, SKINXML)
print "Skinselector: Selected Skin: "+self.root+self.skinfile
restartbox = self.session.openWithCallback(self.restartGUI,MessageBox,_("GUI needs a restart to apply a new skin\nDo you want to restart the GUI now?"), MessageBox.TYPE_YESNO)
restartbox.setTitle(_("Restart GUI now?"))
def loadPreview(self):
if self["SkinList"].getCurrent() == DEFAULTSKIN:
pngpath = "."
else:
pngpath = self["SkinList"].getCurrent()
pngpath = os.path.join(os.path.join(self.root, pngpath), "prev.png")
if not os.path.exists(pngpath):
pngpath = resolveFilename(SCOPE_PLUGINS, "SystemPlugins/SkinSelector/noprev.png")
if self.previewPath != pngpath:
self.previewPath = pngpath
self["Preview"].instance.setPixmapFromFile(self.previewPath)
def restartGUI(self, answer):
if answer is True:
config.skin.primary_skin.value = self.skinfile
config.skin.primary_skin.save()
self.session.open(TryQuitMainloop, 3)
def SkinSelMain(session, **kwargs):
session.open(SkinSelector)
def SkinSelSetup(menuid, **kwargs):
if menuid == "ui_menu":
return [(_("Skin"), SkinSelMain, "skin_selector", None)]
else:
return []
def Plugins(**kwargs):
return PluginDescriptor(name="Skinselector", description="Select Your Skin", where = PluginDescriptor.WHERE_MENU, needsRestart = False, fnc=SkinSelSetup)
| self.skinfile = self["SkinList"].getCurrent() | conditional_block |
plugin.py | # -*- coding: iso-8859-1 -*-
# (c) 2006 Stephan Reichholf
# This Software is Free, use it where you want, when you want for whatever you want and modify it if you want but don't remove my copyright!
from Screens.Screen import Screen
from Screens.Standby import TryQuitMainloop
from Screens.MessageBox import MessageBox
from Components.ActionMap import NumberActionMap
from Components.Pixmap import Pixmap
from Components.Sources.StaticText import StaticText
from Components.MenuList import MenuList
from Plugins.Plugin import PluginDescriptor
from Components.config import config
from Tools.Directories import resolveFilename, SCOPE_PLUGINS
from enigma import eEnv
import os
SKINXML = "skin.xml"
DEFAULTSKIN = "<Default Skin>"
class SkinSelector(Screen):
# for i18n:
# _("Choose your Skin")
skinlist = []
root = os.path.join(eEnv.resolve("${datadir}"),"enigma2")
def __init__(self, session, args = None):
Screen.__init__(self, session)
self.skinlist = []
self.previewPath = ""
if os.path.exists(os.path.join(self.root, SKINXML)):
self.skinlist.append(DEFAULTSKIN)
for root, dirs, files in os.walk(self.root, followlinks=True):
for subdir in dirs:
dir = os.path.join(root,subdir)
if os.path.exists(os.path.join(dir,SKINXML)):
self.skinlist.append(subdir)
dirs = []
self["key_red"] = StaticText(_("Close"))
self["introduction"] = StaticText(_("Press OK to activate the selected skin."))
self.skinlist.sort()
self["SkinList"] = MenuList(self.skinlist)
self["Preview"] = Pixmap()
self["actions"] = NumberActionMap(["WizardActions", "InputActions", "EPGSelectActions"],
{
"ok": self.ok,
"back": self.close,
"red": self.close,
"up": self.up,
"down": self.down,
"left": self.left,
"right": self.right,
"info": self.info,
}, -1)
self.onLayoutFinish.append(self.layoutFinished)
def layoutFinished(self):
tmp = config.skin.primary_skin.value.find("/"+SKINXML)
if tmp != -1:
tmp = config.skin.primary_skin.value[:tmp]
idx = 0
for skin in self.skinlist:
if skin == tmp:
break
idx += 1
if idx < len(self.skinlist):
self["SkinList"].moveToIndex(idx)
self.loadPreview()
def up(self):
self["SkinList"].up()
self.loadPreview()
def down(self):
self["SkinList"].down()
self.loadPreview()
def left(self):
self["SkinList"].pageUp()
self.loadPreview()
| def info(self):
aboutbox = self.session.open(MessageBox,_("STB-GUI Skinselector\n\nIf you experience any problems please contact\nstephan@reichholf.net\n\n\xA9 2006 - Stephan Reichholf"), MessageBox.TYPE_INFO)
aboutbox.setTitle(_("About..."))
def ok(self):
if self["SkinList"].getCurrent() == DEFAULTSKIN:
self.skinfile = "."
else:
self.skinfile = self["SkinList"].getCurrent()
self.skinfile = os.path.join(self.skinfile, SKINXML)
print "Skinselector: Selected Skin: "+self.root+self.skinfile
restartbox = self.session.openWithCallback(self.restartGUI,MessageBox,_("GUI needs a restart to apply a new skin\nDo you want to restart the GUI now?"), MessageBox.TYPE_YESNO)
restartbox.setTitle(_("Restart GUI now?"))
def loadPreview(self):
if self["SkinList"].getCurrent() == DEFAULTSKIN:
pngpath = "."
else:
pngpath = self["SkinList"].getCurrent()
pngpath = os.path.join(os.path.join(self.root, pngpath), "prev.png")
if not os.path.exists(pngpath):
pngpath = resolveFilename(SCOPE_PLUGINS, "SystemPlugins/SkinSelector/noprev.png")
if self.previewPath != pngpath:
self.previewPath = pngpath
self["Preview"].instance.setPixmapFromFile(self.previewPath)
def restartGUI(self, answer):
if answer is True:
config.skin.primary_skin.value = self.skinfile
config.skin.primary_skin.save()
self.session.open(TryQuitMainloop, 3)
def SkinSelMain(session, **kwargs):
session.open(SkinSelector)
def SkinSelSetup(menuid, **kwargs):
if menuid == "ui_menu":
return [(_("Skin"), SkinSelMain, "skin_selector", None)]
else:
return []
def Plugins(**kwargs):
return PluginDescriptor(name="Skinselector", description="Select Your Skin", where = PluginDescriptor.WHERE_MENU, needsRestart = False, fnc=SkinSelSetup) | def right(self):
self["SkinList"].pageDown()
self.loadPreview()
| random_line_split |
plugin.py | # -*- coding: iso-8859-1 -*-
# (c) 2006 Stephan Reichholf
# This Software is Free, use it where you want, when you want for whatever you want and modify it if you want but don't remove my copyright!
from Screens.Screen import Screen
from Screens.Standby import TryQuitMainloop
from Screens.MessageBox import MessageBox
from Components.ActionMap import NumberActionMap
from Components.Pixmap import Pixmap
from Components.Sources.StaticText import StaticText
from Components.MenuList import MenuList
from Plugins.Plugin import PluginDescriptor
from Components.config import config
from Tools.Directories import resolveFilename, SCOPE_PLUGINS
from enigma import eEnv
import os
SKINXML = "skin.xml"
DEFAULTSKIN = "<Default Skin>"
class SkinSelector(Screen):
# for i18n:
# _("Choose your Skin")
skinlist = []
root = os.path.join(eEnv.resolve("${datadir}"),"enigma2")
def __init__(self, session, args = None):
Screen.__init__(self, session)
self.skinlist = []
self.previewPath = ""
if os.path.exists(os.path.join(self.root, SKINXML)):
self.skinlist.append(DEFAULTSKIN)
for root, dirs, files in os.walk(self.root, followlinks=True):
for subdir in dirs:
dir = os.path.join(root,subdir)
if os.path.exists(os.path.join(dir,SKINXML)):
self.skinlist.append(subdir)
dirs = []
self["key_red"] = StaticText(_("Close"))
self["introduction"] = StaticText(_("Press OK to activate the selected skin."))
self.skinlist.sort()
self["SkinList"] = MenuList(self.skinlist)
self["Preview"] = Pixmap()
self["actions"] = NumberActionMap(["WizardActions", "InputActions", "EPGSelectActions"],
{
"ok": self.ok,
"back": self.close,
"red": self.close,
"up": self.up,
"down": self.down,
"left": self.left,
"right": self.right,
"info": self.info,
}, -1)
self.onLayoutFinish.append(self.layoutFinished)
def layoutFinished(self):
tmp = config.skin.primary_skin.value.find("/"+SKINXML)
if tmp != -1:
tmp = config.skin.primary_skin.value[:tmp]
idx = 0
for skin in self.skinlist:
if skin == tmp:
break
idx += 1
if idx < len(self.skinlist):
self["SkinList"].moveToIndex(idx)
self.loadPreview()
def up(self):
self["SkinList"].up()
self.loadPreview()
def down(self):
self["SkinList"].down()
self.loadPreview()
def left(self):
self["SkinList"].pageUp()
self.loadPreview()
def right(self):
self["SkinList"].pageDown()
self.loadPreview()
def info(self):
aboutbox = self.session.open(MessageBox,_("STB-GUI Skinselector\n\nIf you experience any problems please contact\nstephan@reichholf.net\n\n\xA9 2006 - Stephan Reichholf"), MessageBox.TYPE_INFO)
aboutbox.setTitle(_("About..."))
def ok(self):
if self["SkinList"].getCurrent() == DEFAULTSKIN:
self.skinfile = "."
else:
self.skinfile = self["SkinList"].getCurrent()
self.skinfile = os.path.join(self.skinfile, SKINXML)
print "Skinselector: Selected Skin: "+self.root+self.skinfile
restartbox = self.session.openWithCallback(self.restartGUI,MessageBox,_("GUI needs a restart to apply a new skin\nDo you want to restart the GUI now?"), MessageBox.TYPE_YESNO)
restartbox.setTitle(_("Restart GUI now?"))
def loadPreview(self):
if self["SkinList"].getCurrent() == DEFAULTSKIN:
pngpath = "."
else:
pngpath = self["SkinList"].getCurrent()
pngpath = os.path.join(os.path.join(self.root, pngpath), "prev.png")
if not os.path.exists(pngpath):
pngpath = resolveFilename(SCOPE_PLUGINS, "SystemPlugins/SkinSelector/noprev.png")
if self.previewPath != pngpath:
self.previewPath = pngpath
self["Preview"].instance.setPixmapFromFile(self.previewPath)
def restartGUI(self, answer):
if answer is True:
config.skin.primary_skin.value = self.skinfile
config.skin.primary_skin.save()
self.session.open(TryQuitMainloop, 3)
def SkinSelMain(session, **kwargs):
session.open(SkinSelector)
def SkinSelSetup(menuid, **kwargs):
if menuid == "ui_menu":
return [(_("Skin"), SkinSelMain, "skin_selector", None)]
else:
return []
def Plugins(**kwargs):
| return PluginDescriptor(name="Skinselector", description="Select Your Skin", where = PluginDescriptor.WHERE_MENU, needsRestart = False, fnc=SkinSelSetup) | identifier_body | |
sampler_renderer.rs | use core::{Camera, Integrator, Sampler, Scene};
use film::Spectrum;
use linalg::ray_differential::RayDifferential;
use integrator::{SurfaceIntegrator, VolumeIntegrator};
use renderer::Renderer;
pub struct SamplerRenderer<'a, S: Sampler, C: Camera> {
pub sampler: S,
pub camera: C,
pub surface_integrator: &'a SurfaceIntegrator,
pub volume_integrator: &'a VolumeIntegrator,
}
impl<'a, S: Sampler, C: Camera> SamplerRenderer<'a, S, C> {
fn new(sampler: S,
camera: C,
surface_integrator: &'a SurfaceIntegrator,
volume_integrator: &'a VolumeIntegrator)
-> SamplerRenderer<'a, S, C> {
SamplerRenderer {
sampler: sampler,
camera: camera,
surface_integrator: surface_integrator,
volume_integrator: volume_integrator,
}
}
}
impl<'a, S: Sampler, C: Camera> Renderer for SamplerRenderer<'a, S, C> {
fn render(&self, scene: &Scene) |
#[allow(unused_variables)]
fn li(&self, scene: &Scene, ray: &RayDifferential, sample: &Sampler) -> Box<Spectrum> {
unimplemented!()
}
#[allow(unused_variables)]
fn transmittance(&self,
scene: &Scene,
ray: &RayDifferential,
sample: &Sampler)
-> Box<Spectrum> {
unimplemented!()
}
}
| {
self.surface_integrator.preprocess(scene, &self.camera);
self.volume_integrator.preprocess(scene, &self.camera);
} | identifier_body |
sampler_renderer.rs | use core::{Camera, Integrator, Sampler, Scene};
use film::Spectrum;
use linalg::ray_differential::RayDifferential;
use integrator::{SurfaceIntegrator, VolumeIntegrator};
use renderer::Renderer;
pub struct SamplerRenderer<'a, S: Sampler, C: Camera> {
pub sampler: S,
pub camera: C,
pub surface_integrator: &'a SurfaceIntegrator,
pub volume_integrator: &'a VolumeIntegrator, | fn new(sampler: S,
camera: C,
surface_integrator: &'a SurfaceIntegrator,
volume_integrator: &'a VolumeIntegrator)
-> SamplerRenderer<'a, S, C> {
SamplerRenderer {
sampler: sampler,
camera: camera,
surface_integrator: surface_integrator,
volume_integrator: volume_integrator,
}
}
}
impl<'a, S: Sampler, C: Camera> Renderer for SamplerRenderer<'a, S, C> {
fn render(&self, scene: &Scene) {
self.surface_integrator.preprocess(scene, &self.camera);
self.volume_integrator.preprocess(scene, &self.camera);
}
#[allow(unused_variables)]
fn li(&self, scene: &Scene, ray: &RayDifferential, sample: &Sampler) -> Box<Spectrum> {
unimplemented!()
}
#[allow(unused_variables)]
fn transmittance(&self,
scene: &Scene,
ray: &RayDifferential,
sample: &Sampler)
-> Box<Spectrum> {
unimplemented!()
}
} | }
impl<'a, S: Sampler, C: Camera> SamplerRenderer<'a, S, C> { | random_line_split |
sampler_renderer.rs | use core::{Camera, Integrator, Sampler, Scene};
use film::Spectrum;
use linalg::ray_differential::RayDifferential;
use integrator::{SurfaceIntegrator, VolumeIntegrator};
use renderer::Renderer;
pub struct | <'a, S: Sampler, C: Camera> {
pub sampler: S,
pub camera: C,
pub surface_integrator: &'a SurfaceIntegrator,
pub volume_integrator: &'a VolumeIntegrator,
}
impl<'a, S: Sampler, C: Camera> SamplerRenderer<'a, S, C> {
fn new(sampler: S,
camera: C,
surface_integrator: &'a SurfaceIntegrator,
volume_integrator: &'a VolumeIntegrator)
-> SamplerRenderer<'a, S, C> {
SamplerRenderer {
sampler: sampler,
camera: camera,
surface_integrator: surface_integrator,
volume_integrator: volume_integrator,
}
}
}
impl<'a, S: Sampler, C: Camera> Renderer for SamplerRenderer<'a, S, C> {
fn render(&self, scene: &Scene) {
self.surface_integrator.preprocess(scene, &self.camera);
self.volume_integrator.preprocess(scene, &self.camera);
}
#[allow(unused_variables)]
fn li(&self, scene: &Scene, ray: &RayDifferential, sample: &Sampler) -> Box<Spectrum> {
unimplemented!()
}
#[allow(unused_variables)]
fn transmittance(&self,
scene: &Scene,
ray: &RayDifferential,
sample: &Sampler)
-> Box<Spectrum> {
unimplemented!()
}
}
| SamplerRenderer | identifier_name |
app.js | import React, {
Component,
PropTypes
} from 'react';
import {
Provider,
connect
} from 'react-redux';
import {
Button
} from 'local-Antd';
import RoomSelect from 'components/ui-number-select/index.jsx';
import GuestSelect from 'components/ui-hotel-guest/index.jsx';
import NumberSelect from 'components/ui-number/index.jsx';
import Msg from 'components/ui-msg/index.jsx';
import BaseCss from 'local-BaseCss/dist/main.css';
// import UIDiningCity from "components/ui-dining-city/index.jsx";
import GlobleCss from 'components/globleCss/index.scss';
import IndexCss from './sass/index.scss';
class App extends Component {
constructor() {
super();
this.state = {
alertAttrAsyn: this.alertAttrAsyn
}
}
get alertAttr() {
return {
title: '提示1',
content: '<span style="color: red">jfslefjslkfjseokfjowjj</span>',
showFlag: true,
showType: 'confirm', // info alert confirm
backHandle: this._handle.bind(this)
}
}
get alertAttrAsyn() {
return {
asyn: true,
title: '提示2',
content: '<span style="color: red">jfslefjslkfjseokfjowjj</span>',
showFlag: true,
showType: 'alert', // info alert confirm
backHandle: this._handleAsyn.bind(this)
}
}
_handle(key) {
console.log('---_handle' + key);
}
_handleAsyn(key) {
console.log('---_handleAsyn' + key, this.state);
let state = this.alertAttrAsyn;
state.showFlag = false;
if (key == 'ok') {
// 此处假设只有ok按钮异步请求
// 模仿异步请求完成
setTimeout(() => {
this.setState(state);
}, 5000)
}
}
_changeRoom(val) {
console.log('当前房间数', val);
}
_changeGuest(val) {
console.log('当前选择Guest Info', val);
}
_changeNm(val) {
console.log('当前选择Nm Info', val);
}
get showModal() {
return true;
}
get guestInit() {
let childAges = [{
defValue: 2
}, {
defValue: 5
}];
return {
childAges: [],
adultMin: 1,
adultMax: 10,
adultNum: 2,
childMin: 0,
childMax: 5,
childNum: 0,
ageMin: 1,
ageMax: 17,
ageDef: 1,
confirmHandler: this._changeGuest.bind(this),
uiClassName: 'abc'
}
}
renderTest1() {
return (
<RoomSelect defValue="30"
minNum={15}
maxNum={50}
uiClassName="room-select"
uiPlaceholder="选择房间数"
postfix="间"
selectedHandler={this._changeRoom.bind(this)}/>
);
}
renderTest2() {
return ( < NumberSelect defValue = "20"
minNum = {
15
}
maxNum = {
30
}
uiClassName = "nm-select"
uiPlaceholder = "数量"
selectedHandler = {
this._changeNm.bind(this)
}
/>);
}
renderTest3() {
return ( < GuestSelect initData = {
this.guestInit
}
/>
)
}
renderTest4() {
return ( < Msg initData = {
this.state.alertAttrAsyn
} >
<p>{this.state.alertAttrAsyn.content}</p> < /Msg>
)
}
renderTest2() {
return (
<UIDiningCity
keys='name'
data={[{'id' :'1', 'name': '南非'},{'id' : '2', 'name' : '北非'},{'id' : '3', 'name' : '日韩'},{'id' : '4', 'name' : '港澳台'},]}/>
)
}
render() {}
}
|
return Object.assign({}, {})
}
export default connect(mapStateToProps)(App) |
function mapStateToProps(state) { | random_line_split |
app.js | import React, {
Component,
PropTypes
} from 'react';
import {
Provider,
connect
} from 'react-redux';
import {
Button
} from 'local-Antd';
import RoomSelect from 'components/ui-number-select/index.jsx';
import GuestSelect from 'components/ui-hotel-guest/index.jsx';
import NumberSelect from 'components/ui-number/index.jsx';
import Msg from 'components/ui-msg/index.jsx';
import BaseCss from 'local-BaseCss/dist/main.css';
// import UIDiningCity from "components/ui-dining-city/index.jsx";
import GlobleCss from 'components/globleCss/index.scss';
import IndexCss from './sass/index.scss';
class App extends Component {
constructor() {
super();
this.state = {
alertAttrAsyn: this.alertAttrAsyn
}
}
get alertAttr() {
return {
title: '提示1',
content: '<span style="color: red">jfslefjslkfjseokfjowjj</span>',
showFlag: true,
showType: 'confirm', // info alert confirm
backHandle: this._handle.bind(this)
}
}
get alertAttrAsyn() {
return {
asyn: true,
title: '提示2',
content: '<span style="color: red">jfslefjslkfjseokfjowjj</span>',
showFlag: true,
showType: 'alert', // info alert confirm
backHandle: this._handleAsyn.bind(this)
}
}
_handle( | console.log('---_handle' + key);
}
_handleAsyn(key) {
console.log('---_handleAsyn' + key, this.state);
let state = this.alertAttrAsyn;
state.showFlag = false;
if (key == 'ok') {
// 此处假设只有ok按钮异步请求
// 模仿异步请求完成
setTimeout(() => {
this.setState(state);
}, 5000)
}
}
_changeRoom(val) {
console.log('当前房间数', val);
}
_changeGuest(val) {
console.log('当前选择Guest Info', val);
}
_changeNm(val) {
console.log('当前选择Nm Info', val);
}
get showModal() {
return true;
}
get guestInit() {
let childAges = [{
defValue: 2
}, {
defValue: 5
}];
return {
childAges: [],
adultMin: 1,
adultMax: 10,
adultNum: 2,
childMin: 0,
childMax: 5,
childNum: 0,
ageMin: 1,
ageMax: 17,
ageDef: 1,
confirmHandler: this._changeGuest.bind(this),
uiClassName: 'abc'
}
}
renderTest1() {
return (
<RoomSelect defValue="30"
minNum={15}
maxNum={50}
uiClassName="room-select"
uiPlaceholder="选择房间数"
postfix="间"
selectedHandler={this._changeRoom.bind(this)}/>
);
}
renderTest2() {
return ( < NumberSelect defValue = "20"
minNum = {
15
}
maxNum = {
30
}
uiClassName = "nm-select"
uiPlaceholder = "数量"
selectedHandler = {
this._changeNm.bind(this)
}
/>);
}
renderTest3() {
return ( < GuestSelect initData = {
this.guestInit
}
/>
)
}
renderTest4() {
return ( < Msg initData = {
this.state.alertAttrAsyn
} >
<p>{this.state.alertAttrAsyn.content}</p> < /Msg>
)
}
renderTest2() {
return (
<UIDiningCity
keys='name'
data={[{'id' :'1', 'name': '南非'},{'id' : '2', 'name' : '北非'},{'id' : '3', 'name' : '日韩'},{'id' : '4', 'name' : '港澳台'},]}/>
)
}
render() {}
}
function mapStateToProps(state) {
return Object.assign({}, {})
}
export default connect(mapStateToProps)(App) | key) {
| identifier_name |
app.js | import React, {
Component,
PropTypes
} from 'react';
import {
Provider,
connect
} from 'react-redux';
import {
Button
} from 'local-Antd';
import RoomSelect from 'components/ui-number-select/index.jsx';
import GuestSelect from 'components/ui-hotel-guest/index.jsx';
import NumberSelect from 'components/ui-number/index.jsx';
import Msg from 'components/ui-msg/index.jsx';
import BaseCss from 'local-BaseCss/dist/main.css';
// import UIDiningCity from "components/ui-dining-city/index.jsx";
import GlobleCss from 'components/globleCss/index.scss';
import IndexCss from './sass/index.scss';
class App extends Component {
constructor() {
super();
this.state = {
alertAttrAsyn: this.alertAttrAsyn
}
}
get alertAttr() {
return {
title: '提示1',
content: '<span style="color: red">jfslefjslkfjseokfjowjj</span>',
showFlag: true,
showType: 'confirm', // info alert confirm
backHandle: this._handle.bind(this)
}
}
get alertAttrAsyn() {
return {
asyn: true,
title: '提示2',
content: '<span style="color: red">jfslefjslkfjseokfjowjj</span>',
showFlag: true,
showType: 'alert', // info alert confirm
backHandle: this._handleAsyn.bind(this)
}
}
_handle(key) {
console.log('---_handle' + key);
}
_handleAsyn(key) {
co | al);
}
_changeGuest(val) {
console.log('当前选择Guest Info', val);
}
_changeNm(val) {
console.log('当前选择Nm Info', val);
}
get showModal() {
return true;
}
get guestInit() {
let childAges = [{
defValue: 2
}, {
defValue: 5
}];
return {
childAges: [],
adultMin: 1,
adultMax: 10,
adultNum: 2,
childMin: 0,
childMax: 5,
childNum: 0,
ageMin: 1,
ageMax: 17,
ageDef: 1,
confirmHandler: this._changeGuest.bind(this),
uiClassName: 'abc'
}
}
renderTest1() {
return (
<RoomSelect defValue="30"
minNum={15}
maxNum={50}
uiClassName="room-select"
uiPlaceholder="选择房间数"
postfix="间"
selectedHandler={this._changeRoom.bind(this)}/>
);
}
renderTest2() {
return ( < NumberSelect defValue = "20"
minNum = {
15
}
maxNum = {
30
}
uiClassName = "nm-select"
uiPlaceholder = "数量"
selectedHandler = {
this._changeNm.bind(this)
}
/>);
}
renderTest3() {
return ( < GuestSelect initData = {
this.guestInit
}
/>
)
}
renderTest4() {
return ( < Msg initData = {
this.state.alertAttrAsyn
} >
<p>{this.state.alertAttrAsyn.content}</p> < /Msg>
)
}
renderTest2() {
return (
<UIDiningCity
keys='name'
data={[{'id' :'1', 'name': '南非'},{'id' : '2', 'name' : '北非'},{'id' : '3', 'name' : '日韩'},{'id' : '4', 'name' : '港澳台'},]}/>
)
}
render() {}
}
function mapStateToProps(state) {
return Object.assign({}, {})
}
export default connect(mapStateToProps)(App) | nsole.log('---_handleAsyn' + key, this.state);
let state = this.alertAttrAsyn;
state.showFlag = false;
if (key == 'ok') {
// 此处假设只有ok按钮异步请求
// 模仿异步请求完成
setTimeout(() => {
this.setState(state);
}, 5000)
}
}
_changeRoom(val) {
console.log('当前房间数', v | identifier_body |
app.js | import React, {
Component,
PropTypes
} from 'react';
import {
Provider,
connect
} from 'react-redux';
import {
Button
} from 'local-Antd';
import RoomSelect from 'components/ui-number-select/index.jsx';
import GuestSelect from 'components/ui-hotel-guest/index.jsx';
import NumberSelect from 'components/ui-number/index.jsx';
import Msg from 'components/ui-msg/index.jsx';
import BaseCss from 'local-BaseCss/dist/main.css';
// import UIDiningCity from "components/ui-dining-city/index.jsx";
import GlobleCss from 'components/globleCss/index.scss';
import IndexCss from './sass/index.scss';
class App extends Component {
constructor() {
super();
this.state = {
alertAttrAsyn: this.alertAttrAsyn
}
}
get alertAttr() {
return {
title: '提示1',
content: '<span style="color: red">jfslefjslkfjseokfjowjj</span>',
showFlag: true,
showType: 'confirm', // info alert confirm
backHandle: this._handle.bind(this)
}
}
get alertAttrAsyn() {
return {
asyn: true,
title: '提示2',
content: '<span style="color: red">jfslefjslkfjseokfjowjj</span>',
showFlag: true,
showType: 'alert', // info alert confirm
backHandle: this._handleAsyn.bind(this)
}
}
_handle(key) {
console.log('---_handle' + key);
}
_handleAsyn(key) {
console.log('---_handleAsyn' + key, this.state);
let state = this.alertAttrAsyn;
state.showFlag = false;
if (key == 'ok') {
| 数', val);
}
_changeGuest(val) {
console.log('当前选择Guest Info', val);
}
_changeNm(val) {
console.log('当前选择Nm Info', val);
}
get showModal() {
return true;
}
get guestInit() {
let childAges = [{
defValue: 2
}, {
defValue: 5
}];
return {
childAges: [],
adultMin: 1,
adultMax: 10,
adultNum: 2,
childMin: 0,
childMax: 5,
childNum: 0,
ageMin: 1,
ageMax: 17,
ageDef: 1,
confirmHandler: this._changeGuest.bind(this),
uiClassName: 'abc'
}
}
renderTest1() {
return (
<RoomSelect defValue="30"
minNum={15}
maxNum={50}
uiClassName="room-select"
uiPlaceholder="选择房间数"
postfix="间"
selectedHandler={this._changeRoom.bind(this)}/>
);
}
renderTest2() {
return ( < NumberSelect defValue = "20"
minNum = {
15
}
maxNum = {
30
}
uiClassName = "nm-select"
uiPlaceholder = "数量"
selectedHandler = {
this._changeNm.bind(this)
}
/>);
}
renderTest3() {
return ( < GuestSelect initData = {
this.guestInit
}
/>
)
}
renderTest4() {
return ( < Msg initData = {
this.state.alertAttrAsyn
} >
<p>{this.state.alertAttrAsyn.content}</p> < /Msg>
)
}
renderTest2() {
return (
<UIDiningCity
keys='name'
data={[{'id' :'1', 'name': '南非'},{'id' : '2', 'name' : '北非'},{'id' : '3', 'name' : '日韩'},{'id' : '4', 'name' : '港澳台'},]}/>
)
}
render() {}
}
function mapStateToProps(state) {
return Object.assign({}, {})
}
export default connect(mapStateToProps)(App) | // 此处假设只有ok按钮异步请求
// 模仿异步请求完成
setTimeout(() => {
this.setState(state);
}, 5000)
}
}
_changeRoom(val) {
console.log('当前房间 | conditional_block |
crypto.py | """
Django's standard crypto functions and utilities.
""" | import struct
import hashlib
import binascii
import time
# Use the system PRNG if possible
import random
try:
random = random.SystemRandom()
using_sysrandom = True
except NotImplementedError:
import warnings
warnings.warn('A secure pseudo-random number generator is not available '
'on your system. Falling back to Mersenne Twister.')
using_sysrandom = False
from django.conf import settings
from django.utils.encoding import force_bytes
from django.utils import six
from django.utils.six.moves import xrange
def salted_hmac(key_salt, value, secret=None):
"""
Returns the HMAC-SHA1 of 'value', using a key generated from key_salt and a
secret (which defaults to settings.SECRET_KEY).
A different key_salt should be passed in for every application of HMAC.
"""
if secret is None:
secret = settings.SECRET_KEY
key_salt = force_bytes(key_salt)
secret = force_bytes(secret)
# We need to generate a derived key from our base key. We can do this by
# passing the key_salt and our base key through a pseudo-random function and
# SHA1 works nicely.
key = hashlib.sha1(key_salt + secret).digest()
# If len(key_salt + secret) > sha_constructor().block_size, the above
# line is redundant and could be replaced by key = key_salt + secret, since
# the hmac module does the same thing for keys longer than the block size.
# However, we need to ensure that we *always* do this.
return hmac.new(key, msg=force_bytes(value), digestmod=hashlib.sha1)
def get_random_string(length=12,
allowed_chars='abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
"""
Returns a securely generated random string.
The default length of 12 with the a-z, A-Z, 0-9 character set returns
a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
"""
if not using_sysrandom:
# This is ugly, and a hack, but it makes things better than
# the alternative of predictability. This re-seeds the PRNG
# using a value that is hard for an attacker to predict, every
# time a random string is required. This may change the
# properties of the chosen random sequence slightly, but this
# is better than absolute predictability.
random.seed(
hashlib.sha256(
("%s%s%s" % (
random.getstate(),
time.time(),
settings.SECRET_KEY)).encode('utf-8')
).digest())
return ''.join(random.choice(allowed_chars) for i in range(length))
if hasattr(hmac, "compare_digest"):
# Prefer the stdlib implementation, when available.
def constant_time_compare(val1, val2):
return hmac.compare_digest(force_bytes(val1), force_bytes(val2))
else:
def constant_time_compare(val1, val2):
"""
Returns True if the two strings are equal, False otherwise.
The time taken is independent of the number of characters that match.
For the sake of simplicity, this function executes in constant time only
when the two strings have the same length. It short-circuits when they
have different lengths. Since Django only uses it to compare hashes of
known expected length, this is acceptable.
"""
if len(val1) != len(val2):
return False
result = 0
if six.PY3 and isinstance(val1, bytes) and isinstance(val2, bytes):
for x, y in zip(val1, val2):
result |= x ^ y
else:
for x, y in zip(val1, val2):
result |= ord(x) ^ ord(y)
return result == 0
def _bin_to_long(x):
"""
Convert a binary string into a long integer
This is a clever optimization for fast xor vector math
"""
return int(binascii.hexlify(x), 16)
def _long_to_bin(x, hex_format_string):
"""
Convert a long integer into a binary string.
hex_format_string is like "%020x" for padding 10 characters.
"""
return binascii.unhexlify((hex_format_string % x).encode('ascii'))
if hasattr(hashlib, "pbkdf2_hmac"):
def pbkdf2(password, salt, iterations, dklen=0, digest=None):
"""
Implements PBKDF2 with the same API as Django's existing
implementation, using the stdlib.
This is used in Python 2.7.8+ and 3.4+.
"""
if digest is None:
digest = hashlib.sha256
if not dklen:
dklen = None
password = force_bytes(password)
salt = force_bytes(salt)
return hashlib.pbkdf2_hmac(
digest().name, password, salt, iterations, dklen)
else:
def pbkdf2(password, salt, iterations, dklen=0, digest=None):
"""
Implements PBKDF2 as defined in RFC 2898, section 5.2
HMAC+SHA256 is used as the default pseudo random function.
As of 2014, 100,000 iterations was the recommended default which took
100ms on a 2.7Ghz Intel i7 with an optimized implementation. This is
probably the bare minimum for security given 1000 iterations was
recommended in 2001. This code is very well optimized for CPython and
is about five times slower than OpenSSL's implementation. Look in
django.contrib.auth.hashers for the present default, it is lower than
the recommended 100,000 because of the performance difference between
this and an optimized implementation.
"""
assert iterations > 0
if not digest:
digest = hashlib.sha256
password = force_bytes(password)
salt = force_bytes(salt)
hlen = digest().digest_size
if not dklen:
dklen = hlen
if dklen > (2 ** 32 - 1) * hlen:
raise OverflowError('dklen too big')
l = -(-dklen // hlen)
r = dklen - (l - 1) * hlen
hex_format_string = "%%0%ix" % (hlen * 2)
inner, outer = digest(), digest()
if len(password) > inner.block_size:
password = digest(password).digest()
password += b'\x00' * (inner.block_size - len(password))
inner.update(password.translate(hmac.trans_36))
outer.update(password.translate(hmac.trans_5C))
def F(i):
u = salt + struct.pack(b'>I', i)
result = 0
for j in xrange(int(iterations)):
dig1, dig2 = inner.copy(), outer.copy()
dig1.update(u)
dig2.update(dig1.digest())
u = dig2.digest()
result ^= _bin_to_long(u)
return _long_to_bin(result, hex_format_string)
T = [F(x) for x in range(1, l)]
return b''.join(T) + F(l)[:r] | from __future__ import unicode_literals
import hmac | random_line_split |
crypto.py | """
Django's standard crypto functions and utilities.
"""
from __future__ import unicode_literals
import hmac
import struct
import hashlib
import binascii
import time
# Use the system PRNG if possible
import random
try:
random = random.SystemRandom()
using_sysrandom = True
except NotImplementedError:
import warnings
warnings.warn('A secure pseudo-random number generator is not available '
'on your system. Falling back to Mersenne Twister.')
using_sysrandom = False
from django.conf import settings
from django.utils.encoding import force_bytes
from django.utils import six
from django.utils.six.moves import xrange
def salted_hmac(key_salt, value, secret=None):
"""
Returns the HMAC-SHA1 of 'value', using a key generated from key_salt and a
secret (which defaults to settings.SECRET_KEY).
A different key_salt should be passed in for every application of HMAC.
"""
if secret is None:
secret = settings.SECRET_KEY
key_salt = force_bytes(key_salt)
secret = force_bytes(secret)
# We need to generate a derived key from our base key. We can do this by
# passing the key_salt and our base key through a pseudo-random function and
# SHA1 works nicely.
key = hashlib.sha1(key_salt + secret).digest()
# If len(key_salt + secret) > sha_constructor().block_size, the above
# line is redundant and could be replaced by key = key_salt + secret, since
# the hmac module does the same thing for keys longer than the block size.
# However, we need to ensure that we *always* do this.
return hmac.new(key, msg=force_bytes(value), digestmod=hashlib.sha1)
def get_random_string(length=12,
allowed_chars='abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
"""
Returns a securely generated random string.
The default length of 12 with the a-z, A-Z, 0-9 character set returns
a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
"""
if not using_sysrandom:
# This is ugly, and a hack, but it makes things better than
# the alternative of predictability. This re-seeds the PRNG
# using a value that is hard for an attacker to predict, every
# time a random string is required. This may change the
# properties of the chosen random sequence slightly, but this
# is better than absolute predictability.
random.seed(
hashlib.sha256(
("%s%s%s" % (
random.getstate(),
time.time(),
settings.SECRET_KEY)).encode('utf-8')
).digest())
return ''.join(random.choice(allowed_chars) for i in range(length))
if hasattr(hmac, "compare_digest"):
# Prefer the stdlib implementation, when available.
def constant_time_compare(val1, val2):
return hmac.compare_digest(force_bytes(val1), force_bytes(val2))
else:
def | (val1, val2):
"""
Returns True if the two strings are equal, False otherwise.
The time taken is independent of the number of characters that match.
For the sake of simplicity, this function executes in constant time only
when the two strings have the same length. It short-circuits when they
have different lengths. Since Django only uses it to compare hashes of
known expected length, this is acceptable.
"""
if len(val1) != len(val2):
return False
result = 0
if six.PY3 and isinstance(val1, bytes) and isinstance(val2, bytes):
for x, y in zip(val1, val2):
result |= x ^ y
else:
for x, y in zip(val1, val2):
result |= ord(x) ^ ord(y)
return result == 0
def _bin_to_long(x):
"""
Convert a binary string into a long integer
This is a clever optimization for fast xor vector math
"""
return int(binascii.hexlify(x), 16)
def _long_to_bin(x, hex_format_string):
"""
Convert a long integer into a binary string.
hex_format_string is like "%020x" for padding 10 characters.
"""
return binascii.unhexlify((hex_format_string % x).encode('ascii'))
if hasattr(hashlib, "pbkdf2_hmac"):
def pbkdf2(password, salt, iterations, dklen=0, digest=None):
"""
Implements PBKDF2 with the same API as Django's existing
implementation, using the stdlib.
This is used in Python 2.7.8+ and 3.4+.
"""
if digest is None:
digest = hashlib.sha256
if not dklen:
dklen = None
password = force_bytes(password)
salt = force_bytes(salt)
return hashlib.pbkdf2_hmac(
digest().name, password, salt, iterations, dklen)
else:
def pbkdf2(password, salt, iterations, dklen=0, digest=None):
"""
Implements PBKDF2 as defined in RFC 2898, section 5.2
HMAC+SHA256 is used as the default pseudo random function.
As of 2014, 100,000 iterations was the recommended default which took
100ms on a 2.7Ghz Intel i7 with an optimized implementation. This is
probably the bare minimum for security given 1000 iterations was
recommended in 2001. This code is very well optimized for CPython and
is about five times slower than OpenSSL's implementation. Look in
django.contrib.auth.hashers for the present default, it is lower than
the recommended 100,000 because of the performance difference between
this and an optimized implementation.
"""
assert iterations > 0
if not digest:
digest = hashlib.sha256
password = force_bytes(password)
salt = force_bytes(salt)
hlen = digest().digest_size
if not dklen:
dklen = hlen
if dklen > (2 ** 32 - 1) * hlen:
raise OverflowError('dklen too big')
l = -(-dklen // hlen)
r = dklen - (l - 1) * hlen
hex_format_string = "%%0%ix" % (hlen * 2)
inner, outer = digest(), digest()
if len(password) > inner.block_size:
password = digest(password).digest()
password += b'\x00' * (inner.block_size - len(password))
inner.update(password.translate(hmac.trans_36))
outer.update(password.translate(hmac.trans_5C))
def F(i):
u = salt + struct.pack(b'>I', i)
result = 0
for j in xrange(int(iterations)):
dig1, dig2 = inner.copy(), outer.copy()
dig1.update(u)
dig2.update(dig1.digest())
u = dig2.digest()
result ^= _bin_to_long(u)
return _long_to_bin(result, hex_format_string)
T = [F(x) for x in range(1, l)]
return b''.join(T) + F(l)[:r]
| constant_time_compare | identifier_name |
crypto.py | """
Django's standard crypto functions and utilities.
"""
from __future__ import unicode_literals
import hmac
import struct
import hashlib
import binascii
import time
# Use the system PRNG if possible
import random
try:
random = random.SystemRandom()
using_sysrandom = True
except NotImplementedError:
import warnings
warnings.warn('A secure pseudo-random number generator is not available '
'on your system. Falling back to Mersenne Twister.')
using_sysrandom = False
from django.conf import settings
from django.utils.encoding import force_bytes
from django.utils import six
from django.utils.six.moves import xrange
def salted_hmac(key_salt, value, secret=None):
"""
Returns the HMAC-SHA1 of 'value', using a key generated from key_salt and a
secret (which defaults to settings.SECRET_KEY).
A different key_salt should be passed in for every application of HMAC.
"""
if secret is None:
secret = settings.SECRET_KEY
key_salt = force_bytes(key_salt)
secret = force_bytes(secret)
# We need to generate a derived key from our base key. We can do this by
# passing the key_salt and our base key through a pseudo-random function and
# SHA1 works nicely.
key = hashlib.sha1(key_salt + secret).digest()
# If len(key_salt + secret) > sha_constructor().block_size, the above
# line is redundant and could be replaced by key = key_salt + secret, since
# the hmac module does the same thing for keys longer than the block size.
# However, we need to ensure that we *always* do this.
return hmac.new(key, msg=force_bytes(value), digestmod=hashlib.sha1)
def get_random_string(length=12,
allowed_chars='abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
"""
Returns a securely generated random string.
The default length of 12 with the a-z, A-Z, 0-9 character set returns
a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
"""
if not using_sysrandom:
# This is ugly, and a hack, but it makes things better than
# the alternative of predictability. This re-seeds the PRNG
# using a value that is hard for an attacker to predict, every
# time a random string is required. This may change the
# properties of the chosen random sequence slightly, but this
# is better than absolute predictability.
random.seed(
hashlib.sha256(
("%s%s%s" % (
random.getstate(),
time.time(),
settings.SECRET_KEY)).encode('utf-8')
).digest())
return ''.join(random.choice(allowed_chars) for i in range(length))
if hasattr(hmac, "compare_digest"):
# Prefer the stdlib implementation, when available.
def constant_time_compare(val1, val2):
|
else:
def constant_time_compare(val1, val2):
"""
Returns True if the two strings are equal, False otherwise.
The time taken is independent of the number of characters that match.
For the sake of simplicity, this function executes in constant time only
when the two strings have the same length. It short-circuits when they
have different lengths. Since Django only uses it to compare hashes of
known expected length, this is acceptable.
"""
if len(val1) != len(val2):
return False
result = 0
if six.PY3 and isinstance(val1, bytes) and isinstance(val2, bytes):
for x, y in zip(val1, val2):
result |= x ^ y
else:
for x, y in zip(val1, val2):
result |= ord(x) ^ ord(y)
return result == 0
def _bin_to_long(x):
"""
Convert a binary string into a long integer
This is a clever optimization for fast xor vector math
"""
return int(binascii.hexlify(x), 16)
def _long_to_bin(x, hex_format_string):
"""
Convert a long integer into a binary string.
hex_format_string is like "%020x" for padding 10 characters.
"""
return binascii.unhexlify((hex_format_string % x).encode('ascii'))
if hasattr(hashlib, "pbkdf2_hmac"):
def pbkdf2(password, salt, iterations, dklen=0, digest=None):
"""
Implements PBKDF2 with the same API as Django's existing
implementation, using the stdlib.
This is used in Python 2.7.8+ and 3.4+.
"""
if digest is None:
digest = hashlib.sha256
if not dklen:
dklen = None
password = force_bytes(password)
salt = force_bytes(salt)
return hashlib.pbkdf2_hmac(
digest().name, password, salt, iterations, dklen)
else:
def pbkdf2(password, salt, iterations, dklen=0, digest=None):
"""
Implements PBKDF2 as defined in RFC 2898, section 5.2
HMAC+SHA256 is used as the default pseudo random function.
As of 2014, 100,000 iterations was the recommended default which took
100ms on a 2.7Ghz Intel i7 with an optimized implementation. This is
probably the bare minimum for security given 1000 iterations was
recommended in 2001. This code is very well optimized for CPython and
is about five times slower than OpenSSL's implementation. Look in
django.contrib.auth.hashers for the present default, it is lower than
the recommended 100,000 because of the performance difference between
this and an optimized implementation.
"""
assert iterations > 0
if not digest:
digest = hashlib.sha256
password = force_bytes(password)
salt = force_bytes(salt)
hlen = digest().digest_size
if not dklen:
dklen = hlen
if dklen > (2 ** 32 - 1) * hlen:
raise OverflowError('dklen too big')
l = -(-dklen // hlen)
r = dklen - (l - 1) * hlen
hex_format_string = "%%0%ix" % (hlen * 2)
inner, outer = digest(), digest()
if len(password) > inner.block_size:
password = digest(password).digest()
password += b'\x00' * (inner.block_size - len(password))
inner.update(password.translate(hmac.trans_36))
outer.update(password.translate(hmac.trans_5C))
def F(i):
u = salt + struct.pack(b'>I', i)
result = 0
for j in xrange(int(iterations)):
dig1, dig2 = inner.copy(), outer.copy()
dig1.update(u)
dig2.update(dig1.digest())
u = dig2.digest()
result ^= _bin_to_long(u)
return _long_to_bin(result, hex_format_string)
T = [F(x) for x in range(1, l)]
return b''.join(T) + F(l)[:r]
| return hmac.compare_digest(force_bytes(val1), force_bytes(val2)) | identifier_body |
crypto.py | """
Django's standard crypto functions and utilities.
"""
from __future__ import unicode_literals
import hmac
import struct
import hashlib
import binascii
import time
# Use the system PRNG if possible
import random
try:
random = random.SystemRandom()
using_sysrandom = True
except NotImplementedError:
import warnings
warnings.warn('A secure pseudo-random number generator is not available '
'on your system. Falling back to Mersenne Twister.')
using_sysrandom = False
from django.conf import settings
from django.utils.encoding import force_bytes
from django.utils import six
from django.utils.six.moves import xrange
def salted_hmac(key_salt, value, secret=None):
"""
Returns the HMAC-SHA1 of 'value', using a key generated from key_salt and a
secret (which defaults to settings.SECRET_KEY).
A different key_salt should be passed in for every application of HMAC.
"""
if secret is None:
secret = settings.SECRET_KEY
key_salt = force_bytes(key_salt)
secret = force_bytes(secret)
# We need to generate a derived key from our base key. We can do this by
# passing the key_salt and our base key through a pseudo-random function and
# SHA1 works nicely.
key = hashlib.sha1(key_salt + secret).digest()
# If len(key_salt + secret) > sha_constructor().block_size, the above
# line is redundant and could be replaced by key = key_salt + secret, since
# the hmac module does the same thing for keys longer than the block size.
# However, we need to ensure that we *always* do this.
return hmac.new(key, msg=force_bytes(value), digestmod=hashlib.sha1)
def get_random_string(length=12,
allowed_chars='abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
"""
Returns a securely generated random string.
The default length of 12 with the a-z, A-Z, 0-9 character set returns
a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
"""
if not using_sysrandom:
# This is ugly, and a hack, but it makes things better than
# the alternative of predictability. This re-seeds the PRNG
# using a value that is hard for an attacker to predict, every
# time a random string is required. This may change the
# properties of the chosen random sequence slightly, but this
# is better than absolute predictability.
random.seed(
hashlib.sha256(
("%s%s%s" % (
random.getstate(),
time.time(),
settings.SECRET_KEY)).encode('utf-8')
).digest())
return ''.join(random.choice(allowed_chars) for i in range(length))
if hasattr(hmac, "compare_digest"):
# Prefer the stdlib implementation, when available.
|
else:
def constant_time_compare(val1, val2):
"""
Returns True if the two strings are equal, False otherwise.
The time taken is independent of the number of characters that match.
For the sake of simplicity, this function executes in constant time only
when the two strings have the same length. It short-circuits when they
have different lengths. Since Django only uses it to compare hashes of
known expected length, this is acceptable.
"""
if len(val1) != len(val2):
return False
result = 0
if six.PY3 and isinstance(val1, bytes) and isinstance(val2, bytes):
for x, y in zip(val1, val2):
result |= x ^ y
else:
for x, y in zip(val1, val2):
result |= ord(x) ^ ord(y)
return result == 0
def _bin_to_long(x):
"""
Convert a binary string into a long integer
This is a clever optimization for fast xor vector math
"""
return int(binascii.hexlify(x), 16)
def _long_to_bin(x, hex_format_string):
"""
Convert a long integer into a binary string.
hex_format_string is like "%020x" for padding 10 characters.
"""
return binascii.unhexlify((hex_format_string % x).encode('ascii'))
if hasattr(hashlib, "pbkdf2_hmac"):
def pbkdf2(password, salt, iterations, dklen=0, digest=None):
"""
Implements PBKDF2 with the same API as Django's existing
implementation, using the stdlib.
This is used in Python 2.7.8+ and 3.4+.
"""
if digest is None:
digest = hashlib.sha256
if not dklen:
dklen = None
password = force_bytes(password)
salt = force_bytes(salt)
return hashlib.pbkdf2_hmac(
digest().name, password, salt, iterations, dklen)
else:
def pbkdf2(password, salt, iterations, dklen=0, digest=None):
"""
Implements PBKDF2 as defined in RFC 2898, section 5.2
HMAC+SHA256 is used as the default pseudo random function.
As of 2014, 100,000 iterations was the recommended default which took
100ms on a 2.7Ghz Intel i7 with an optimized implementation. This is
probably the bare minimum for security given 1000 iterations was
recommended in 2001. This code is very well optimized for CPython and
is about five times slower than OpenSSL's implementation. Look in
django.contrib.auth.hashers for the present default, it is lower than
the recommended 100,000 because of the performance difference between
this and an optimized implementation.
"""
assert iterations > 0
if not digest:
digest = hashlib.sha256
password = force_bytes(password)
salt = force_bytes(salt)
hlen = digest().digest_size
if not dklen:
dklen = hlen
if dklen > (2 ** 32 - 1) * hlen:
raise OverflowError('dklen too big')
l = -(-dklen // hlen)
r = dklen - (l - 1) * hlen
hex_format_string = "%%0%ix" % (hlen * 2)
inner, outer = digest(), digest()
if len(password) > inner.block_size:
password = digest(password).digest()
password += b'\x00' * (inner.block_size - len(password))
inner.update(password.translate(hmac.trans_36))
outer.update(password.translate(hmac.trans_5C))
def F(i):
u = salt + struct.pack(b'>I', i)
result = 0
for j in xrange(int(iterations)):
dig1, dig2 = inner.copy(), outer.copy()
dig1.update(u)
dig2.update(dig1.digest())
u = dig2.digest()
result ^= _bin_to_long(u)
return _long_to_bin(result, hex_format_string)
T = [F(x) for x in range(1, l)]
return b''.join(T) + F(l)[:r]
| def constant_time_compare(val1, val2):
return hmac.compare_digest(force_bytes(val1), force_bytes(val2)) | conditional_block |
rmeta.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms. | // aux-build:rmeta_rlib.rs
extern crate rmeta_aux;
use rmeta_aux::Foo;
pub fn main() {
let _ = Foo { field: 42 };
} |
// Test that using rlibs and rmeta dep crates work together. Specifically, that
// there can be both an rmeta and an rlib file and rustc will prefer the rlib.
// aux-build:rmeta_rmeta.rs | random_line_split |
rmeta.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that using rlibs and rmeta dep crates work together. Specifically, that
// there can be both an rmeta and an rlib file and rustc will prefer the rlib.
// aux-build:rmeta_rmeta.rs
// aux-build:rmeta_rlib.rs
extern crate rmeta_aux;
use rmeta_aux::Foo;
pub fn main() | {
let _ = Foo { field: 42 };
} | identifier_body | |
rmeta.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that using rlibs and rmeta dep crates work together. Specifically, that
// there can be both an rmeta and an rlib file and rustc will prefer the rlib.
// aux-build:rmeta_rmeta.rs
// aux-build:rmeta_rlib.rs
extern crate rmeta_aux;
use rmeta_aux::Foo;
pub fn | () {
let _ = Foo { field: 42 };
}
| main | identifier_name |
parsers.py | import csv
from gff3 import Gff3
import gff3
gff3.gff3.logger.setLevel(100)
import io, re
from urllib import parse
SNPEFF_REGEX = re.compile(r"(\w+)\((.+)\)")
def parse_genes(gff3_file, go_terms_file):
"""parses the genes from gff3 and enriches it with additional information"""
go_map = _get_go_map(go_terms_file)
gff = Gff3(gff3_file)
genes = [line for line in gff.lines if line['line_type'] == 'feature' and line['type'] == 'gene']
genes_map = {}
for gene in genes:
gene_id = gene['attributes']['ID']
symbol = gene['attributes'].get('symbol',None)
full_name = gene['attributes'].get('full_name',None)
aliases = gene['attributes'].get('Alias',[])
aliases = [{'symbol':aliases[i],'full_name':(None if i>=len(aliases)-1 else aliases[i+1])} for i in range(0,len(aliases),2)]
if symbol and full_name:
aliases.insert(0,{'symbol': symbol,'full_name':full_name})
gene_dict = {'positions':{'gte':gene['start'],'lte': gene['end']},
'chr':gene['seqid'].lower(),'type':gene['type'],
'strand':gene['strand'],'name':gene_id,
'aliases':aliases,'isoforms':[],'GO':go_map.get(gene_id,[])}
gene_dict['isoforms'] = _parse_isoforms(gff, gene)
genes_map[gene_id] = gene_dict
gene_dict['suggest'] = [gene_id]
gene_dict['suggest'].extend(set([alias['symbol'] for alias in gene_dict['aliases']]))
return genes_map
def _parse_isoforms(gff, gene):
isoforms = []
for mRNA in gff.descendants(gene):
# skip sub features because they are stored within the isoform below
if mRNA['type'] in ['CDS', 'exon','three_prime_UTR', 'five_prime_UTR']:
continue
cds = []
exons = []
five_prime_UTR = []
three_prime_UTR = []
for feature in gff.descendants(mRNA):
feature_dict = {'positions':{'gte':feature['start'],'lte':feature['end']}}
if feature['type'] == 'CDS':
feature_dict['frame'] = feature['phase']
cds.append(feature_dict)
elif feature['type'] == 'exon':
exons.append(feature_dict)
elif feature['type'] == 'three_prime_UTR':
three_prime_UTR.append(feature_dict)
elif feature['type'] == 'five_prime_UTR':
five_prime_UTR.append(feature_dict)
else:
continue
mRNA_id = mRNA['attributes']['ID']
short_description = mRNA['attributes'].get('Note',[None])[0]
curator_summary = mRNA['attributes'].get('curator_summary',None)
description = mRNA['attributes'].get('computational_description',None)
mRNA_dict = {'positions': {'gte':mRNA['start'],'lte':mRNA['end']},
'strand':mRNA['strand'],'name':mRNA_id,'type':mRNA['type'],
'cds':cds,'exons':exons, 'five_prime_UTR': five_prime_UTR, 'three_prime_UTR': three_prime_UTR}
if short_description:
mRNA_dict['short_description'] = parse.unquote(short_description)
if curator_summary:
mRNA_dict['curator_summary'] = parse.unquote(curator_summary)
if description:
mRNA_dict['description'] = parse.unquote(description)
isoforms.append(mRNA_dict)
return isoforms
def _parse_snpeff_infos(genotype, info):
infos = info.split(";")[-1].split("=")[-1].split(",")
annotations = []
coding = False
gene_name = None
for info in infos:
matches = SNPEFF_REGEX.match(info)
if not matches or len(matches.groups()) != 2:
return (coding, annotations, gene_name)
annotation = {'effect':matches.group(1)}
fields = matches.group(2).split("|")
if genotype != None and fields[-1] != genotype:
continue
annotation['impact'] = fields[0]
if fields[1] != '':
annotation['function'] = fields[1]
if fields[2] != '':
annotation['codon_change'] = fields[2]
if fields[3] != '':
annotation['amino_acid_change'] = fields[3]
if fields[5] != '':
annotation['gene_name'] = fields[5]
if gene_name is None:
gene_name = annotation['gene_name']
coding = True
if fields[8] != '':
annotation['transcript_id'] = fields[8]
if fields[9] != '':
try:
annotation['rank'] = int(fields[9])
except:
pass
annotations.append(annotation)
return coding, annotations, gene_name
def parse_snpeff(snp, is_custom_snp_eff):
"""parses the snpeff fields"""
anc = ''
if is_custom_snp_eff:
anc = snp[4]
if anc == '0':
anc = snp[2]
elif anc == '1':
anc = snp[3]
chrom = snp[0].lower()
pos = int(snp[1])
if is_custom_snp_eff:
ref = snp[2]
alt = snp[3]
genotype = snp[5]
info = snp[6]
else:
ref = snp[3]
alt = snp[4]
genotype = None
info = snp[7]
document = {'chr': chrom, 'position': pos, 'ref': ref, 'alt': alt, 'anc': anc}
coding, annotations, gene_name = _parse_snpeff_infos(genotype, info)
document['coding'] = coding
if coding and gene_name:
document['gene_name'] = gene_name
document['annotations'] = annotations
return document
def parse_lastel(last_el):
# Need to transform _ to # and check if string contains square brackets
if last_el[0] == '[':
last_el = last_el[1:-1]
last = last_el.split(',')
print(last)
score = float(last[0])
uid = '#'.join(last[1][1:-1].split('-'))
return [score, uid]
def _get_go_map(filename):
go_dict = {}
with open(filename, 'r') as fh:
reader = csv.reader(fh, delimiter='\t')
for row in reader:
gene_id = row[0]
go = {'object_name':row[2], 'relation':row[3],'term':row[4],'slim_term':row[8], 'go_id':row[5]}
if gene_id not in go_dict:
|
go_dict[gene_id].append(go)
return go_dict
| go_dict[gene_id] = [] | conditional_block |
parsers.py | import csv
from gff3 import Gff3
import gff3
gff3.gff3.logger.setLevel(100)
import io, re
from urllib import parse
SNPEFF_REGEX = re.compile(r"(\w+)\((.+)\)")
def parse_genes(gff3_file, go_terms_file):
"""parses the genes from gff3 and enriches it with additional information"""
go_map = _get_go_map(go_terms_file)
gff = Gff3(gff3_file)
genes = [line for line in gff.lines if line['line_type'] == 'feature' and line['type'] == 'gene']
genes_map = {}
for gene in genes:
gene_id = gene['attributes']['ID']
symbol = gene['attributes'].get('symbol',None)
full_name = gene['attributes'].get('full_name',None)
aliases = gene['attributes'].get('Alias',[])
aliases = [{'symbol':aliases[i],'full_name':(None if i>=len(aliases)-1 else aliases[i+1])} for i in range(0,len(aliases),2)]
if symbol and full_name:
aliases.insert(0,{'symbol': symbol,'full_name':full_name})
gene_dict = {'positions':{'gte':gene['start'],'lte': gene['end']},
'chr':gene['seqid'].lower(),'type':gene['type'],
'strand':gene['strand'],'name':gene_id,
'aliases':aliases,'isoforms':[],'GO':go_map.get(gene_id,[])}
gene_dict['isoforms'] = _parse_isoforms(gff, gene)
genes_map[gene_id] = gene_dict
gene_dict['suggest'] = [gene_id]
gene_dict['suggest'].extend(set([alias['symbol'] for alias in gene_dict['aliases']]))
return genes_map
def _parse_isoforms(gff, gene):
isoforms = []
for mRNA in gff.descendants(gene):
# skip sub features because they are stored within the isoform below
if mRNA['type'] in ['CDS', 'exon','three_prime_UTR', 'five_prime_UTR']:
continue
cds = []
exons = []
five_prime_UTR = []
three_prime_UTR = []
for feature in gff.descendants(mRNA):
feature_dict = {'positions':{'gte':feature['start'],'lte':feature['end']}}
if feature['type'] == 'CDS':
feature_dict['frame'] = feature['phase']
cds.append(feature_dict)
elif feature['type'] == 'exon':
exons.append(feature_dict)
elif feature['type'] == 'three_prime_UTR':
three_prime_UTR.append(feature_dict)
elif feature['type'] == 'five_prime_UTR':
five_prime_UTR.append(feature_dict)
else:
continue
mRNA_id = mRNA['attributes']['ID']
short_description = mRNA['attributes'].get('Note',[None])[0]
curator_summary = mRNA['attributes'].get('curator_summary',None)
description = mRNA['attributes'].get('computational_description',None)
mRNA_dict = {'positions': {'gte':mRNA['start'],'lte':mRNA['end']},
'strand':mRNA['strand'],'name':mRNA_id,'type':mRNA['type'],
'cds':cds,'exons':exons, 'five_prime_UTR': five_prime_UTR, 'three_prime_UTR': three_prime_UTR}
if short_description:
mRNA_dict['short_description'] = parse.unquote(short_description)
if curator_summary:
mRNA_dict['curator_summary'] = parse.unquote(curator_summary)
if description:
mRNA_dict['description'] = parse.unquote(description)
isoforms.append(mRNA_dict)
return isoforms
def _parse_snpeff_infos(genotype, info):
infos = info.split(";")[-1].split("=")[-1].split(",")
annotations = []
coding = False
gene_name = None
for info in infos:
matches = SNPEFF_REGEX.match(info)
if not matches or len(matches.groups()) != 2:
return (coding, annotations, gene_name)
annotation = {'effect':matches.group(1)}
fields = matches.group(2).split("|")
if genotype != None and fields[-1] != genotype:
continue
annotation['impact'] = fields[0]
if fields[1] != '':
annotation['function'] = fields[1]
if fields[2] != '':
annotation['codon_change'] = fields[2]
if fields[3] != '':
annotation['amino_acid_change'] = fields[3]
if fields[5] != '':
annotation['gene_name'] = fields[5]
if gene_name is None: | if fields[9] != '':
try:
annotation['rank'] = int(fields[9])
except:
pass
annotations.append(annotation)
return coding, annotations, gene_name
def parse_snpeff(snp, is_custom_snp_eff):
"""parses the snpeff fields"""
anc = ''
if is_custom_snp_eff:
anc = snp[4]
if anc == '0':
anc = snp[2]
elif anc == '1':
anc = snp[3]
chrom = snp[0].lower()
pos = int(snp[1])
if is_custom_snp_eff:
ref = snp[2]
alt = snp[3]
genotype = snp[5]
info = snp[6]
else:
ref = snp[3]
alt = snp[4]
genotype = None
info = snp[7]
document = {'chr': chrom, 'position': pos, 'ref': ref, 'alt': alt, 'anc': anc}
coding, annotations, gene_name = _parse_snpeff_infos(genotype, info)
document['coding'] = coding
if coding and gene_name:
document['gene_name'] = gene_name
document['annotations'] = annotations
return document
def parse_lastel(last_el):
# Need to transform _ to # and check if string contains square brackets
if last_el[0] == '[':
last_el = last_el[1:-1]
last = last_el.split(',')
print(last)
score = float(last[0])
uid = '#'.join(last[1][1:-1].split('-'))
return [score, uid]
def _get_go_map(filename):
go_dict = {}
with open(filename, 'r') as fh:
reader = csv.reader(fh, delimiter='\t')
for row in reader:
gene_id = row[0]
go = {'object_name':row[2], 'relation':row[3],'term':row[4],'slim_term':row[8], 'go_id':row[5]}
if gene_id not in go_dict:
go_dict[gene_id] = []
go_dict[gene_id].append(go)
return go_dict | gene_name = annotation['gene_name']
coding = True
if fields[8] != '':
annotation['transcript_id'] = fields[8] | random_line_split |
parsers.py | import csv
from gff3 import Gff3
import gff3
gff3.gff3.logger.setLevel(100)
import io, re
from urllib import parse
SNPEFF_REGEX = re.compile(r"(\w+)\((.+)\)")
def parse_genes(gff3_file, go_terms_file):
"""parses the genes from gff3 and enriches it with additional information"""
go_map = _get_go_map(go_terms_file)
gff = Gff3(gff3_file)
genes = [line for line in gff.lines if line['line_type'] == 'feature' and line['type'] == 'gene']
genes_map = {}
for gene in genes:
gene_id = gene['attributes']['ID']
symbol = gene['attributes'].get('symbol',None)
full_name = gene['attributes'].get('full_name',None)
aliases = gene['attributes'].get('Alias',[])
aliases = [{'symbol':aliases[i],'full_name':(None if i>=len(aliases)-1 else aliases[i+1])} for i in range(0,len(aliases),2)]
if symbol and full_name:
aliases.insert(0,{'symbol': symbol,'full_name':full_name})
gene_dict = {'positions':{'gte':gene['start'],'lte': gene['end']},
'chr':gene['seqid'].lower(),'type':gene['type'],
'strand':gene['strand'],'name':gene_id,
'aliases':aliases,'isoforms':[],'GO':go_map.get(gene_id,[])}
gene_dict['isoforms'] = _parse_isoforms(gff, gene)
genes_map[gene_id] = gene_dict
gene_dict['suggest'] = [gene_id]
gene_dict['suggest'].extend(set([alias['symbol'] for alias in gene_dict['aliases']]))
return genes_map
def _parse_isoforms(gff, gene):
isoforms = []
for mRNA in gff.descendants(gene):
# skip sub features because they are stored within the isoform below
if mRNA['type'] in ['CDS', 'exon','three_prime_UTR', 'five_prime_UTR']:
continue
cds = []
exons = []
five_prime_UTR = []
three_prime_UTR = []
for feature in gff.descendants(mRNA):
feature_dict = {'positions':{'gte':feature['start'],'lte':feature['end']}}
if feature['type'] == 'CDS':
feature_dict['frame'] = feature['phase']
cds.append(feature_dict)
elif feature['type'] == 'exon':
exons.append(feature_dict)
elif feature['type'] == 'three_prime_UTR':
three_prime_UTR.append(feature_dict)
elif feature['type'] == 'five_prime_UTR':
five_prime_UTR.append(feature_dict)
else:
continue
mRNA_id = mRNA['attributes']['ID']
short_description = mRNA['attributes'].get('Note',[None])[0]
curator_summary = mRNA['attributes'].get('curator_summary',None)
description = mRNA['attributes'].get('computational_description',None)
mRNA_dict = {'positions': {'gte':mRNA['start'],'lte':mRNA['end']},
'strand':mRNA['strand'],'name':mRNA_id,'type':mRNA['type'],
'cds':cds,'exons':exons, 'five_prime_UTR': five_prime_UTR, 'three_prime_UTR': three_prime_UTR}
if short_description:
mRNA_dict['short_description'] = parse.unquote(short_description)
if curator_summary:
mRNA_dict['curator_summary'] = parse.unquote(curator_summary)
if description:
mRNA_dict['description'] = parse.unquote(description)
isoforms.append(mRNA_dict)
return isoforms
def _parse_snpeff_infos(genotype, info):
infos = info.split(";")[-1].split("=")[-1].split(",")
annotations = []
coding = False
gene_name = None
for info in infos:
matches = SNPEFF_REGEX.match(info)
if not matches or len(matches.groups()) != 2:
return (coding, annotations, gene_name)
annotation = {'effect':matches.group(1)}
fields = matches.group(2).split("|")
if genotype != None and fields[-1] != genotype:
continue
annotation['impact'] = fields[0]
if fields[1] != '':
annotation['function'] = fields[1]
if fields[2] != '':
annotation['codon_change'] = fields[2]
if fields[3] != '':
annotation['amino_acid_change'] = fields[3]
if fields[5] != '':
annotation['gene_name'] = fields[5]
if gene_name is None:
gene_name = annotation['gene_name']
coding = True
if fields[8] != '':
annotation['transcript_id'] = fields[8]
if fields[9] != '':
try:
annotation['rank'] = int(fields[9])
except:
pass
annotations.append(annotation)
return coding, annotations, gene_name
def parse_snpeff(snp, is_custom_snp_eff):
|
def parse_lastel(last_el):
# Need to transform _ to # and check if string contains square brackets
if last_el[0] == '[':
last_el = last_el[1:-1]
last = last_el.split(',')
print(last)
score = float(last[0])
uid = '#'.join(last[1][1:-1].split('-'))
return [score, uid]
def _get_go_map(filename):
go_dict = {}
with open(filename, 'r') as fh:
reader = csv.reader(fh, delimiter='\t')
for row in reader:
gene_id = row[0]
go = {'object_name':row[2], 'relation':row[3],'term':row[4],'slim_term':row[8], 'go_id':row[5]}
if gene_id not in go_dict:
go_dict[gene_id] = []
go_dict[gene_id].append(go)
return go_dict
| """parses the snpeff fields"""
anc = ''
if is_custom_snp_eff:
anc = snp[4]
if anc == '0':
anc = snp[2]
elif anc == '1':
anc = snp[3]
chrom = snp[0].lower()
pos = int(snp[1])
if is_custom_snp_eff:
ref = snp[2]
alt = snp[3]
genotype = snp[5]
info = snp[6]
else:
ref = snp[3]
alt = snp[4]
genotype = None
info = snp[7]
document = {'chr': chrom, 'position': pos, 'ref': ref, 'alt': alt, 'anc': anc}
coding, annotations, gene_name = _parse_snpeff_infos(genotype, info)
document['coding'] = coding
if coding and gene_name:
document['gene_name'] = gene_name
document['annotations'] = annotations
return document | identifier_body |
parsers.py | import csv
from gff3 import Gff3
import gff3
gff3.gff3.logger.setLevel(100)
import io, re
from urllib import parse
SNPEFF_REGEX = re.compile(r"(\w+)\((.+)\)")
def | (gff3_file, go_terms_file):
"""parses the genes from gff3 and enriches it with additional information"""
go_map = _get_go_map(go_terms_file)
gff = Gff3(gff3_file)
genes = [line for line in gff.lines if line['line_type'] == 'feature' and line['type'] == 'gene']
genes_map = {}
for gene in genes:
gene_id = gene['attributes']['ID']
symbol = gene['attributes'].get('symbol',None)
full_name = gene['attributes'].get('full_name',None)
aliases = gene['attributes'].get('Alias',[])
aliases = [{'symbol':aliases[i],'full_name':(None if i>=len(aliases)-1 else aliases[i+1])} for i in range(0,len(aliases),2)]
if symbol and full_name:
aliases.insert(0,{'symbol': symbol,'full_name':full_name})
gene_dict = {'positions':{'gte':gene['start'],'lte': gene['end']},
'chr':gene['seqid'].lower(),'type':gene['type'],
'strand':gene['strand'],'name':gene_id,
'aliases':aliases,'isoforms':[],'GO':go_map.get(gene_id,[])}
gene_dict['isoforms'] = _parse_isoforms(gff, gene)
genes_map[gene_id] = gene_dict
gene_dict['suggest'] = [gene_id]
gene_dict['suggest'].extend(set([alias['symbol'] for alias in gene_dict['aliases']]))
return genes_map
def _parse_isoforms(gff, gene):
isoforms = []
for mRNA in gff.descendants(gene):
# skip sub features because they are stored within the isoform below
if mRNA['type'] in ['CDS', 'exon','three_prime_UTR', 'five_prime_UTR']:
continue
cds = []
exons = []
five_prime_UTR = []
three_prime_UTR = []
for feature in gff.descendants(mRNA):
feature_dict = {'positions':{'gte':feature['start'],'lte':feature['end']}}
if feature['type'] == 'CDS':
feature_dict['frame'] = feature['phase']
cds.append(feature_dict)
elif feature['type'] == 'exon':
exons.append(feature_dict)
elif feature['type'] == 'three_prime_UTR':
three_prime_UTR.append(feature_dict)
elif feature['type'] == 'five_prime_UTR':
five_prime_UTR.append(feature_dict)
else:
continue
mRNA_id = mRNA['attributes']['ID']
short_description = mRNA['attributes'].get('Note',[None])[0]
curator_summary = mRNA['attributes'].get('curator_summary',None)
description = mRNA['attributes'].get('computational_description',None)
mRNA_dict = {'positions': {'gte':mRNA['start'],'lte':mRNA['end']},
'strand':mRNA['strand'],'name':mRNA_id,'type':mRNA['type'],
'cds':cds,'exons':exons, 'five_prime_UTR': five_prime_UTR, 'three_prime_UTR': three_prime_UTR}
if short_description:
mRNA_dict['short_description'] = parse.unquote(short_description)
if curator_summary:
mRNA_dict['curator_summary'] = parse.unquote(curator_summary)
if description:
mRNA_dict['description'] = parse.unquote(description)
isoforms.append(mRNA_dict)
return isoforms
def _parse_snpeff_infos(genotype, info):
infos = info.split(";")[-1].split("=")[-1].split(",")
annotations = []
coding = False
gene_name = None
for info in infos:
matches = SNPEFF_REGEX.match(info)
if not matches or len(matches.groups()) != 2:
return (coding, annotations, gene_name)
annotation = {'effect':matches.group(1)}
fields = matches.group(2).split("|")
if genotype != None and fields[-1] != genotype:
continue
annotation['impact'] = fields[0]
if fields[1] != '':
annotation['function'] = fields[1]
if fields[2] != '':
annotation['codon_change'] = fields[2]
if fields[3] != '':
annotation['amino_acid_change'] = fields[3]
if fields[5] != '':
annotation['gene_name'] = fields[5]
if gene_name is None:
gene_name = annotation['gene_name']
coding = True
if fields[8] != '':
annotation['transcript_id'] = fields[8]
if fields[9] != '':
try:
annotation['rank'] = int(fields[9])
except:
pass
annotations.append(annotation)
return coding, annotations, gene_name
def parse_snpeff(snp, is_custom_snp_eff):
"""parses the snpeff fields"""
anc = ''
if is_custom_snp_eff:
anc = snp[4]
if anc == '0':
anc = snp[2]
elif anc == '1':
anc = snp[3]
chrom = snp[0].lower()
pos = int(snp[1])
if is_custom_snp_eff:
ref = snp[2]
alt = snp[3]
genotype = snp[5]
info = snp[6]
else:
ref = snp[3]
alt = snp[4]
genotype = None
info = snp[7]
document = {'chr': chrom, 'position': pos, 'ref': ref, 'alt': alt, 'anc': anc}
coding, annotations, gene_name = _parse_snpeff_infos(genotype, info)
document['coding'] = coding
if coding and gene_name:
document['gene_name'] = gene_name
document['annotations'] = annotations
return document
def parse_lastel(last_el):
# Need to transform _ to # and check if string contains square brackets
if last_el[0] == '[':
last_el = last_el[1:-1]
last = last_el.split(',')
print(last)
score = float(last[0])
uid = '#'.join(last[1][1:-1].split('-'))
return [score, uid]
def _get_go_map(filename):
go_dict = {}
with open(filename, 'r') as fh:
reader = csv.reader(fh, delimiter='\t')
for row in reader:
gene_id = row[0]
go = {'object_name':row[2], 'relation':row[3],'term':row[4],'slim_term':row[8], 'go_id':row[5]}
if gene_id not in go_dict:
go_dict[gene_id] = []
go_dict[gene_id].append(go)
return go_dict
| parse_genes | identifier_name |
app.js | 'use strict';
var path = require('path'),
logger = require('morgan'),
express = require('express'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser');
var routes = require('./routes/index');
var app = express();
app.config = require((process.env.NODE_ENV === 'test') ? './config-test' : './config');
// View engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// Logging middleware
if (app.get('env') === 'development') {
app.use(logger('dev'));
}
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/api/health', require('./routes/health'));
// Catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// Error handlers
// Development error handler
// Will print stacktrace
if (app.get('env') === 'development') |
// Production error handler
// No stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
| {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
} | conditional_block |
app.js | 'use strict';
var path = require('path'),
logger = require('morgan'),
express = require('express'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser');
var routes = require('./routes/index');
var app = express();
app.config = require((process.env.NODE_ENV === 'test') ? './config-test' : './config');
// View engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// Logging middleware
if (app.get('env') === 'development') {
app.use(logger('dev'));
}
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/api/health', require('./routes/health'));
// Catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// Error handlers
// Development error handler
// Will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err |
// Production error handler
// No stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app; | });
});
} | random_line_split |
main.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as path from 'canonical-path';
import * as yargs from 'yargs';
import {checkMarkerFile, writeMarkerFile} from './packages/build_marker';
import {DependencyHost} from './packages/dependency_host';
import {DependencyResolver} from './packages/dependency_resolver';
import {EntryPointFormat} from './packages/entry_point';
import {makeEntryPointBundle} from './packages/entry_point_bundle';
import {EntryPointFinder} from './packages/entry_point_finder';
import {Transformer} from './packages/transformer';
export function mainNgcc(args: string[]): number {
const options =
yargs
.option('s', {
alias: 'source',
describe: 'A path to the root folder to compile.',
default: './node_modules'
})
.option('f', {
alias: 'formats',
array: true,
describe: 'An array of formats to compile.',
default: ['fesm2015', 'esm2015', 'fesm5', 'esm5']
})
.option('t', {
alias: 'target',
describe: 'A path to a root folder where the compiled files will be written.',
defaultDescription: 'The `source` folder.'
})
.help()
.parse(args);
const sourcePath: string = path.resolve(options['s']);
const formats: EntryPointFormat[] = options['f'];
const targetPath: string = options['t'] || sourcePath;
const transformer = new Transformer(sourcePath, targetPath);
const host = new DependencyHost();
const resolver = new DependencyResolver(host);
const finder = new EntryPointFinder(resolver);
try {
const {entryPoints} = finder.findEntryPoints(sourcePath);
entryPoints.forEach(entryPoint => {
// Are we compiling the Angular core?
const isCore = entryPoint.name === '@angular/core';
// We transform the d.ts typings files while transforming one of the formats.
// This variable decides with which of the available formats to do this transform.
// It is marginally faster to process via the flat file if available.
const dtsTransformFormat: EntryPointFormat = entryPoint.fesm2015 ? 'fesm2015' : 'esm2015';
formats.forEach(format => {
if (checkMarkerFile(entryPoint, format)) { | console.warn(`Skipping ${entryPoint.name} : ${format} (already built).`);
return;
}
const bundle =
makeEntryPointBundle(entryPoint, isCore, format, format === dtsTransformFormat);
if (bundle === null) {
console.warn(
`Skipping ${entryPoint.name} : ${format} (no entry point file for this format).`);
} else {
transformer.transform(entryPoint, isCore, bundle);
}
// Write the built-with-ngcc marker
writeMarkerFile(entryPoint, format);
});
});
} catch (e) {
console.error(e.stack);
return 1;
}
return 0;
} | random_line_split | |
main.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as path from 'canonical-path';
import * as yargs from 'yargs';
import {checkMarkerFile, writeMarkerFile} from './packages/build_marker';
import {DependencyHost} from './packages/dependency_host';
import {DependencyResolver} from './packages/dependency_resolver';
import {EntryPointFormat} from './packages/entry_point';
import {makeEntryPointBundle} from './packages/entry_point_bundle';
import {EntryPointFinder} from './packages/entry_point_finder';
import {Transformer} from './packages/transformer';
export function | (args: string[]): number {
const options =
yargs
.option('s', {
alias: 'source',
describe: 'A path to the root folder to compile.',
default: './node_modules'
})
.option('f', {
alias: 'formats',
array: true,
describe: 'An array of formats to compile.',
default: ['fesm2015', 'esm2015', 'fesm5', 'esm5']
})
.option('t', {
alias: 'target',
describe: 'A path to a root folder where the compiled files will be written.',
defaultDescription: 'The `source` folder.'
})
.help()
.parse(args);
const sourcePath: string = path.resolve(options['s']);
const formats: EntryPointFormat[] = options['f'];
const targetPath: string = options['t'] || sourcePath;
const transformer = new Transformer(sourcePath, targetPath);
const host = new DependencyHost();
const resolver = new DependencyResolver(host);
const finder = new EntryPointFinder(resolver);
try {
const {entryPoints} = finder.findEntryPoints(sourcePath);
entryPoints.forEach(entryPoint => {
// Are we compiling the Angular core?
const isCore = entryPoint.name === '@angular/core';
// We transform the d.ts typings files while transforming one of the formats.
// This variable decides with which of the available formats to do this transform.
// It is marginally faster to process via the flat file if available.
const dtsTransformFormat: EntryPointFormat = entryPoint.fesm2015 ? 'fesm2015' : 'esm2015';
formats.forEach(format => {
if (checkMarkerFile(entryPoint, format)) {
console.warn(`Skipping ${entryPoint.name} : ${format} (already built).`);
return;
}
const bundle =
makeEntryPointBundle(entryPoint, isCore, format, format === dtsTransformFormat);
if (bundle === null) {
console.warn(
`Skipping ${entryPoint.name} : ${format} (no entry point file for this format).`);
} else {
transformer.transform(entryPoint, isCore, bundle);
}
// Write the built-with-ngcc marker
writeMarkerFile(entryPoint, format);
});
});
} catch (e) {
console.error(e.stack);
return 1;
}
return 0;
}
| mainNgcc | identifier_name |
main.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as path from 'canonical-path';
import * as yargs from 'yargs';
import {checkMarkerFile, writeMarkerFile} from './packages/build_marker';
import {DependencyHost} from './packages/dependency_host';
import {DependencyResolver} from './packages/dependency_resolver';
import {EntryPointFormat} from './packages/entry_point';
import {makeEntryPointBundle} from './packages/entry_point_bundle';
import {EntryPointFinder} from './packages/entry_point_finder';
import {Transformer} from './packages/transformer';
export function mainNgcc(args: string[]): number {
const options =
yargs
.option('s', {
alias: 'source',
describe: 'A path to the root folder to compile.',
default: './node_modules'
})
.option('f', {
alias: 'formats',
array: true,
describe: 'An array of formats to compile.',
default: ['fesm2015', 'esm2015', 'fesm5', 'esm5']
})
.option('t', {
alias: 'target',
describe: 'A path to a root folder where the compiled files will be written.',
defaultDescription: 'The `source` folder.'
})
.help()
.parse(args);
const sourcePath: string = path.resolve(options['s']);
const formats: EntryPointFormat[] = options['f'];
const targetPath: string = options['t'] || sourcePath;
const transformer = new Transformer(sourcePath, targetPath);
const host = new DependencyHost();
const resolver = new DependencyResolver(host);
const finder = new EntryPointFinder(resolver);
try {
const {entryPoints} = finder.findEntryPoints(sourcePath);
entryPoints.forEach(entryPoint => {
// Are we compiling the Angular core?
const isCore = entryPoint.name === '@angular/core';
// We transform the d.ts typings files while transforming one of the formats.
// This variable decides with which of the available formats to do this transform.
// It is marginally faster to process via the flat file if available.
const dtsTransformFormat: EntryPointFormat = entryPoint.fesm2015 ? 'fesm2015' : 'esm2015';
formats.forEach(format => {
if (checkMarkerFile(entryPoint, format)) |
const bundle =
makeEntryPointBundle(entryPoint, isCore, format, format === dtsTransformFormat);
if (bundle === null) {
console.warn(
`Skipping ${entryPoint.name} : ${format} (no entry point file for this format).`);
} else {
transformer.transform(entryPoint, isCore, bundle);
}
// Write the built-with-ngcc marker
writeMarkerFile(entryPoint, format);
});
});
} catch (e) {
console.error(e.stack);
return 1;
}
return 0;
}
| {
console.warn(`Skipping ${entryPoint.name} : ${format} (already built).`);
return;
} | conditional_block |
main.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as path from 'canonical-path';
import * as yargs from 'yargs';
import {checkMarkerFile, writeMarkerFile} from './packages/build_marker';
import {DependencyHost} from './packages/dependency_host';
import {DependencyResolver} from './packages/dependency_resolver';
import {EntryPointFormat} from './packages/entry_point';
import {makeEntryPointBundle} from './packages/entry_point_bundle';
import {EntryPointFinder} from './packages/entry_point_finder';
import {Transformer} from './packages/transformer';
export function mainNgcc(args: string[]): number | {
const options =
yargs
.option('s', {
alias: 'source',
describe: 'A path to the root folder to compile.',
default: './node_modules'
})
.option('f', {
alias: 'formats',
array: true,
describe: 'An array of formats to compile.',
default: ['fesm2015', 'esm2015', 'fesm5', 'esm5']
})
.option('t', {
alias: 'target',
describe: 'A path to a root folder where the compiled files will be written.',
defaultDescription: 'The `source` folder.'
})
.help()
.parse(args);
const sourcePath: string = path.resolve(options['s']);
const formats: EntryPointFormat[] = options['f'];
const targetPath: string = options['t'] || sourcePath;
const transformer = new Transformer(sourcePath, targetPath);
const host = new DependencyHost();
const resolver = new DependencyResolver(host);
const finder = new EntryPointFinder(resolver);
try {
const {entryPoints} = finder.findEntryPoints(sourcePath);
entryPoints.forEach(entryPoint => {
// Are we compiling the Angular core?
const isCore = entryPoint.name === '@angular/core';
// We transform the d.ts typings files while transforming one of the formats.
// This variable decides with which of the available formats to do this transform.
// It is marginally faster to process via the flat file if available.
const dtsTransformFormat: EntryPointFormat = entryPoint.fesm2015 ? 'fesm2015' : 'esm2015';
formats.forEach(format => {
if (checkMarkerFile(entryPoint, format)) {
console.warn(`Skipping ${entryPoint.name} : ${format} (already built).`);
return;
}
const bundle =
makeEntryPointBundle(entryPoint, isCore, format, format === dtsTransformFormat);
if (bundle === null) {
console.warn(
`Skipping ${entryPoint.name} : ${format} (no entry point file for this format).`);
} else {
transformer.transform(entryPoint, isCore, bundle);
}
// Write the built-with-ngcc marker
writeMarkerFile(entryPoint, format);
});
});
} catch (e) {
console.error(e.stack);
return 1;
}
return 0;
} | identifier_body | |
test_database_upgrade_service.py | '''
Created on 28.06.2016
@author: michael
'''
import unittest
from alexandriabase.services import DatabaseUpgradeService
from daotests.test_base import DatabaseBaseTest
from alexandriabase.daos import RegistryDao
class DatabaseUpgradeServiceTest(DatabaseBaseTest):
|
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main() | def setUp(self):
super().setUp()
self.upgrade_service = DatabaseUpgradeService(self.engine)
def tearDown(self):
super().tearDown()
def testUpgrade(self):
self.assertTrue(self.upgrade_service.is_update_necessary())
self.upgrade_service.run_update()
self.assertFalse(self.upgrade_service.is_update_necessary())
def testFailingUpgrade(self):
registry_dao = RegistryDao(self.engine)
registry_dao.set('version', 'not_existing')
self.assertTrue(self.upgrade_service.is_update_necessary())
expected_exception = False
try:
self.upgrade_service.run_update()
except Exception:
expected_exception = True
self.assertTrue(expected_exception) | identifier_body |
test_database_upgrade_service.py | '''
Created on 28.06.2016
@author: michael
'''
import unittest
from alexandriabase.services import DatabaseUpgradeService
from daotests.test_base import DatabaseBaseTest
from alexandriabase.daos import RegistryDao
class DatabaseUpgradeServiceTest(DatabaseBaseTest):
def setUp(self):
super().setUp()
self.upgrade_service = DatabaseUpgradeService(self.engine)
def tearDown(self):
super().tearDown()
def testUpgrade(self):
self.assertTrue(self.upgrade_service.is_update_necessary())
self.upgrade_service.run_update()
self.assertFalse(self.upgrade_service.is_update_necessary())
def testFailingUpgrade(self):
registry_dao = RegistryDao(self.engine)
registry_dao.set('version', 'not_existing')
self.assertTrue(self.upgrade_service.is_update_necessary())
expected_exception = False
try:
self.upgrade_service.run_update()
except Exception:
expected_exception = True
self.assertTrue(expected_exception)
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
| unittest.main() | conditional_block | |
test_database_upgrade_service.py | '''
Created on 28.06.2016
@author: michael
'''
import unittest
from alexandriabase.services import DatabaseUpgradeService
from daotests.test_base import DatabaseBaseTest
from alexandriabase.daos import RegistryDao
class DatabaseUpgradeServiceTest(DatabaseBaseTest):
def setUp(self):
super().setUp()
self.upgrade_service = DatabaseUpgradeService(self.engine)
def tearDown(self):
super().tearDown()
def testUpgrade(self):
self.assertTrue(self.upgrade_service.is_update_necessary())
self.upgrade_service.run_update()
self.assertFalse(self.upgrade_service.is_update_necessary())
def | (self):
registry_dao = RegistryDao(self.engine)
registry_dao.set('version', 'not_existing')
self.assertTrue(self.upgrade_service.is_update_necessary())
expected_exception = False
try:
self.upgrade_service.run_update()
except Exception:
expected_exception = True
self.assertTrue(expected_exception)
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main() | testFailingUpgrade | identifier_name |
test_database_upgrade_service.py | '''
Created on 28.06.2016
@author: michael
'''
import unittest
from alexandriabase.services import DatabaseUpgradeService
from daotests.test_base import DatabaseBaseTest
from alexandriabase.daos import RegistryDao
class DatabaseUpgradeServiceTest(DatabaseBaseTest):
def setUp(self):
super().setUp()
self.upgrade_service = DatabaseUpgradeService(self.engine)
def tearDown(self):
super().tearDown()
def testUpgrade(self):
self.assertTrue(self.upgrade_service.is_update_necessary()) | registry_dao.set('version', 'not_existing')
self.assertTrue(self.upgrade_service.is_update_necessary())
expected_exception = False
try:
self.upgrade_service.run_update()
except Exception:
expected_exception = True
self.assertTrue(expected_exception)
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main() | self.upgrade_service.run_update()
self.assertFalse(self.upgrade_service.is_update_necessary())
def testFailingUpgrade(self):
registry_dao = RegistryDao(self.engine) | random_line_split |
opera.d.ts | import * as webdriver from "./index";
import * as remote from "./remote";
declare namespace opera {
/**
* Creates {@link remote.DriverService} instances that manages an
* [OperaDriver](https://github.com/operasoftware/operachromiumdriver)
* server in a child process.
*/
class ServiceBuilder {
/**
* @param {string=} opt_exe Path to the server executable to use. If omitted,
* the builder will attempt to locate the operadriver on the current
* PATH.
* @throws {Error} If provided executable does not exist, or the operadriver
* cannot be found on the PATH.
*/
constructor(opt_exe?: string);
/**
* Sets the port to start the OperaDriver on.
* @param {number} port The port to use, or 0 for any free port.
* @return {!ServiceBuilder} A self reference.
* @throws {Error} If the port is invalid.
*/
usingPort(port: number): ServiceBuilder;
/**
* Sets the path of the log file the driver should log to. If a log file is
* not specified, the driver will log to stderr.
* @param {string} path Path of the log file to use.
* @return {!ServiceBuilder} A self reference.
*/
loggingTo(path: string): ServiceBuilder;
/**
* Enables verbose logging.
* @return {!ServiceBuilder} A self reference.
*/
enableVerboseLogging(): ServiceBuilder;
/**
* Silence sthe drivers output.
* @return {!ServiceBuilder} A self reference.
*/
silent(): ServiceBuilder;
/**
* Defines the stdio configuration for the driver service. See
* {@code child_process.spawn} for more information.
* @param {(string|!Array<string|number|!stream.Stream|null|undefined>)}
* config The configuration to use.
* @return {!ServiceBuilder} A self reference.
*/
setStdio(config: string | Array<string | number | any>): ServiceBuilder;
/**
* Defines the environment to start the server under. This settings will be
* inherited by every browser session started by the server.
* @param {!Object.<string, string>} env The environment to use.
* @return {!ServiceBuilder} A self reference.
*/
withEnvironment(env: Object): ServiceBuilder;
/**
* Creates a new DriverService using this instance's current configuration.
* @return {!remote.DriverService} A new driver service using this instance's
* current configuration.
* @throws {Error} If the driver exectuable was not specified and a default
* could not be found on the current PATH.
*/
build(): remote.DriverService;
}
/**
* Sets the default service to use for new OperaDriver instances.
* @param {!remote.DriverService} service The service to use.
* @throws {Error} If the default service is currently running.
*/
function setDefaultService(service: remote.DriverService): any;
/**
* Returns the default OperaDriver service. If such a service has not been
* configured, one will be constructed using the default configuration for
* a OperaDriver executable found on the system PATH.
* @return {!remote.DriverService} The default OperaDriver service.
*/
function getDefaultService(): remote.DriverService;
/**
* Class for managing {@linkplain Driver OperaDriver} specific options.
*/
class Options {
/**
* Extracts the OperaDriver specific options from the given capabilities
* object.
* @param {!capabilities.Capabilities} caps The capabilities object.
* @return {!Options} The OperaDriver options.
*/
static fromCapabilities(caps: webdriver.Capabilities): Options;
/**
* Add additional command line arguments to use when launching the Opera
* browser. Each argument may be specified with or without the "--" prefix
* (e.g. "--foo" and "foo"). Arguments with an associated value should be
* delimited by an "=": "foo=bar".
* @param {...(string|!Array.<string>)} var_args The arguments to add.
* @return {!Options} A self reference.
*/
addArguments(...var_args: Array<string>): Options;
/**
* Add additional extensions to install when launching Opera. Each extension
* should be specified as the path to the packed CRX file, or a Buffer for an
* extension.
* @param {...(string|!Buffer|!Array.<(string|!Buffer)>)} var_args The
* extensions to add.
* @return {!Options} A self reference.
*/
addExtensions(...var_args: Array<any>): Options;
/**
* Sets the path to the Opera binary to use. On Mac OS X, this path should
* reference the actual Opera executable, not just the application binary. The
* binary path be absolute or relative to the operadriver server executable, but
* it must exist on the machine that will launch Opera.
*
* @param {string} path The path to the Opera binary to use.
* @return {!Options} A self reference.
*/
setOperaBinaryPath(path: string): Options;
/**
* Sets the logging preferences for the new session.
* @param {!./lib/logging.Preferences} prefs The logging preferences.
* @return {!Options} A self reference.
*/
setLoggingPrefs(prefs: webdriver.logging.Preferences): Options;
/**
* Sets the proxy settings for the new session. | * @param {capabilities.ProxyConfig} proxy The proxy configuration to use.
* @return {!Options} A self reference.
*/
setProxy(proxy: webdriver.ProxyConfig): Options;
/**
* Converts this options instance to a {@link capabilities.Capabilities}
* object.
* @param {capabilities.Capabilities=} opt_capabilities The capabilities to
* merge these options into, if any.
* @return {!capabilities.Capabilities} The capabilities.
*/
toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities;
}
class Driver extends webdriver.WebDriver {
/**
* @param {(capabilities.Capabilities|Options)=} opt_config The configuration
* options.
* @param {remote.DriverService=} opt_service The session to use; will use
* the {@link getDefaultService default service} by default.
* @param {promise.ControlFlow=} opt_flow The control flow to use,
* or {@code null} to use the currently active flow.
*/
constructor(opt_config?: webdriver.Capabilities | Options, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow);
/**
* This function is a no-op as file detectors are not supported by this
* implementation.
* @override
*/
setFileDetector(): void;
}
}
export = opera; | random_line_split | |
opera.d.ts | import * as webdriver from "./index";
import * as remote from "./remote";
declare namespace opera {
/**
* Creates {@link remote.DriverService} instances that manages an
* [OperaDriver](https://github.com/operasoftware/operachromiumdriver)
* server in a child process.
*/
class | {
/**
* @param {string=} opt_exe Path to the server executable to use. If omitted,
* the builder will attempt to locate the operadriver on the current
* PATH.
* @throws {Error} If provided executable does not exist, or the operadriver
* cannot be found on the PATH.
*/
constructor(opt_exe?: string);
/**
* Sets the port to start the OperaDriver on.
* @param {number} port The port to use, or 0 for any free port.
* @return {!ServiceBuilder} A self reference.
* @throws {Error} If the port is invalid.
*/
usingPort(port: number): ServiceBuilder;
/**
* Sets the path of the log file the driver should log to. If a log file is
* not specified, the driver will log to stderr.
* @param {string} path Path of the log file to use.
* @return {!ServiceBuilder} A self reference.
*/
loggingTo(path: string): ServiceBuilder;
/**
* Enables verbose logging.
* @return {!ServiceBuilder} A self reference.
*/
enableVerboseLogging(): ServiceBuilder;
/**
* Silence sthe drivers output.
* @return {!ServiceBuilder} A self reference.
*/
silent(): ServiceBuilder;
/**
* Defines the stdio configuration for the driver service. See
* {@code child_process.spawn} for more information.
* @param {(string|!Array<string|number|!stream.Stream|null|undefined>)}
* config The configuration to use.
* @return {!ServiceBuilder} A self reference.
*/
setStdio(config: string | Array<string | number | any>): ServiceBuilder;
/**
* Defines the environment to start the server under. This settings will be
* inherited by every browser session started by the server.
* @param {!Object.<string, string>} env The environment to use.
* @return {!ServiceBuilder} A self reference.
*/
withEnvironment(env: Object): ServiceBuilder;
/**
* Creates a new DriverService using this instance's current configuration.
* @return {!remote.DriverService} A new driver service using this instance's
* current configuration.
* @throws {Error} If the driver exectuable was not specified and a default
* could not be found on the current PATH.
*/
build(): remote.DriverService;
}
/**
* Sets the default service to use for new OperaDriver instances.
* @param {!remote.DriverService} service The service to use.
* @throws {Error} If the default service is currently running.
*/
function setDefaultService(service: remote.DriverService): any;
/**
* Returns the default OperaDriver service. If such a service has not been
* configured, one will be constructed using the default configuration for
* a OperaDriver executable found on the system PATH.
* @return {!remote.DriverService} The default OperaDriver service.
*/
function getDefaultService(): remote.DriverService;
/**
* Class for managing {@linkplain Driver OperaDriver} specific options.
*/
class Options {
/**
* Extracts the OperaDriver specific options from the given capabilities
* object.
* @param {!capabilities.Capabilities} caps The capabilities object.
* @return {!Options} The OperaDriver options.
*/
static fromCapabilities(caps: webdriver.Capabilities): Options;
/**
* Add additional command line arguments to use when launching the Opera
* browser. Each argument may be specified with or without the "--" prefix
* (e.g. "--foo" and "foo"). Arguments with an associated value should be
* delimited by an "=": "foo=bar".
* @param {...(string|!Array.<string>)} var_args The arguments to add.
* @return {!Options} A self reference.
*/
addArguments(...var_args: Array<string>): Options;
/**
* Add additional extensions to install when launching Opera. Each extension
* should be specified as the path to the packed CRX file, or a Buffer for an
* extension.
* @param {...(string|!Buffer|!Array.<(string|!Buffer)>)} var_args The
* extensions to add.
* @return {!Options} A self reference.
*/
addExtensions(...var_args: Array<any>): Options;
/**
* Sets the path to the Opera binary to use. On Mac OS X, this path should
* reference the actual Opera executable, not just the application binary. The
* binary path be absolute or relative to the operadriver server executable, but
* it must exist on the machine that will launch Opera.
*
* @param {string} path The path to the Opera binary to use.
* @return {!Options} A self reference.
*/
setOperaBinaryPath(path: string): Options;
/**
* Sets the logging preferences for the new session.
* @param {!./lib/logging.Preferences} prefs The logging preferences.
* @return {!Options} A self reference.
*/
setLoggingPrefs(prefs: webdriver.logging.Preferences): Options;
/**
* Sets the proxy settings for the new session.
* @param {capabilities.ProxyConfig} proxy The proxy configuration to use.
* @return {!Options} A self reference.
*/
setProxy(proxy: webdriver.ProxyConfig): Options;
/**
* Converts this options instance to a {@link capabilities.Capabilities}
* object.
* @param {capabilities.Capabilities=} opt_capabilities The capabilities to
* merge these options into, if any.
* @return {!capabilities.Capabilities} The capabilities.
*/
toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities;
}
class Driver extends webdriver.WebDriver {
/**
* @param {(capabilities.Capabilities|Options)=} opt_config The configuration
* options.
* @param {remote.DriverService=} opt_service The session to use; will use
* the {@link getDefaultService default service} by default.
* @param {promise.ControlFlow=} opt_flow The control flow to use,
* or {@code null} to use the currently active flow.
*/
constructor(opt_config?: webdriver.Capabilities | Options, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow);
/**
* This function is a no-op as file detectors are not supported by this
* implementation.
* @override
*/
setFileDetector(): void;
}
}
export = opera; | ServiceBuilder | identifier_name |
OLA_nl_NL.ts | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="nl_NL">
<context> | <location filename="configureolaio.ui" line="14"/>
<source>Configure OLA I/O</source>
<translation>Configureer OLA I/O</translation>
</message>
<message>
<location filename="configureolaio.ui" line="21"/>
<source>Output</source>
<translation>Output</translation>
</message>
<message>
<location filename="configureolaio.ui" line="26"/>
<source>OLA Universe</source>
<translation>OLA Universe</translation>
</message>
<message>
<location filename="configureolaio.ui" line="34"/>
<source>Run standalone OLA daemon</source>
<translation>Run standalone OLA daemon</translation>
</message>
</context>
<context>
<name>OlaIO</name>
<message>
<location filename="olaio.cpp" line="152"/>
<source>This plugin provides DMX output support for the Open Lighting Architecture (OLA).</source>
<translation>Deze plugin verzorgt DMX output voor de Open Lighting Architecture (OLA).</translation>
</message>
<message>
<location filename="olaio.cpp" line="166"/>
<source>This is the output for OLA universe %1</source>
<translation>Dit is de output voor OLA Universe %1</translation>
</message>
</context>
</TS> | <name>ConfigureOlaIO</name>
<message> | random_line_split |
metadata.rs | use ape;
use id3;
use lewton::inside_ogg::OggStreamReader;
use metaflac;
use mp3_duration;
use regex::Regex;
use std::fs;
use std::path::Path;
use errors::*;
use utils;
use utils::AudioFormat;
#[derive(Debug, Clone, PartialEq)]
pub struct SongTags {
pub disc_number: Option<u32>,
pub track_number: Option<u32>,
pub title: Option<String>,
pub duration: Option<u32>,
pub artist: Option<String>,
pub album_artist: Option<String>,
pub album: Option<String>,
pub year: Option<i32>,
}
pub fn read(path: &Path) -> Result<SongTags> {
match utils::get_audio_format(path) {
Some(AudioFormat::FLAC) => read_flac(path),
Some(AudioFormat::MP3) => read_id3(path),
Some(AudioFormat::MPC) => read_ape(path),
Some(AudioFormat::OGG) => read_vorbis(path),
_ => bail!("Unsupported file format for reading metadata"),
}
}
fn read_id3(path: &Path) -> Result<SongTags> {
let tag = id3::Tag::read_from_path(&path)?;
let duration = mp3_duration::from_path(&path).map(|d| d.as_secs() as u32).ok();
let artist = tag.artist().map(|s| s.to_string());
let album_artist = tag.album_artist().map(|s| s.to_string());
let album = tag.album().map(|s| s.to_string());
let title = tag.title().map(|s| s.to_string());
let disc_number = tag.disc();
let track_number = tag.track();
let year = tag.year()
.map(|y| y as i32)
.or(tag.date_released().and_then(|d| Some(d.year)))
.or(tag.date_recorded().and_then(|d| Some(d.year)));
Ok(SongTags {
artist: artist,
album_artist: album_artist,
album: album,
title: title,
duration: duration,
disc_number: disc_number,
track_number: track_number,
year: year,
})
}
fn read_ape_string(item: &ape::Item) -> Option<String> {
match item.value {
ape::ItemValue::Text(ref s) => Some(s.clone()),
_ => None,
}
}
fn read_ape_i32(item: &ape::Item) -> Option<i32> {
match item.value {
ape::ItemValue::Text(ref s) => s.parse::<i32>().ok(),
_ => None,
}
}
fn read_ape_x_of_y(item: &ape::Item) -> Option<u32> {
match item.value {
ape::ItemValue::Text(ref s) => {
let format = Regex::new(r#"^\d+"#).unwrap();
if let Some(m) = format.find(s) {
s[m.start()..m.end()].parse().ok()
} else {
None
}
}
_ => None,
}
}
fn read_ape(path: &Path) -> Result<SongTags> {
let tag = ape::read(path)?;
let artist = tag.item("Artist").and_then(read_ape_string);
let album = tag.item("Album").and_then(read_ape_string);
let album_artist = tag.item("Album artist").and_then(read_ape_string);
let title = tag.item("Title").and_then(read_ape_string);
let year = tag.item("Year").and_then(read_ape_i32);
let disc_number = tag.item("Disc").and_then(read_ape_x_of_y);
let track_number = tag.item("Track").and_then(read_ape_x_of_y);
Ok(SongTags {
artist: artist,
album_artist: album_artist,
album: album,
title: title,
duration: None,
disc_number: disc_number,
track_number: track_number,
year: year,
})
}
fn read_vorbis(path: &Path) -> Result<SongTags> {
let file = fs::File::open(path)?;
let source = OggStreamReader::new(file)?;
let mut tags = SongTags {
artist: None,
album_artist: None,
album: None,
title: None,
duration:None,
disc_number: None,
track_number: None,
year: None,
};
for (key, value) in source.comment_hdr.comment_list {
match key.as_str() {
"TITLE" => tags.title = Some(value),
"ALBUM" => tags.album = Some(value),
"ARTIST" => tags.artist = Some(value),
"ALBUMARTIST" => tags.album_artist = Some(value),
"TRACKNUMBER" => tags.track_number = value.parse::<u32>().ok(),
"DISCNUMBER" => tags.disc_number = value.parse::<u32>().ok(),
"DATE" => tags.year = value.parse::<i32>().ok(),
_ => (),
}
}
Ok(tags)
}
fn read_flac(path: &Path) -> Result<SongTags> {
let tag = metaflac::Tag::read_from_path(path)?;
let vorbis = tag.vorbis_comments().ok_or("Missing Vorbis comments")?;
let disc_number = vorbis
.get("DISCNUMBER")
.and_then(|d| d[0].parse::<u32>().ok());
let year = vorbis.get("DATE").and_then(|d| d[0].parse::<i32>().ok());
let streaminfo = tag.get_blocks(metaflac::BlockType::StreamInfo);
let duration = match streaminfo.first() {
Some(&&metaflac::Block::StreamInfo(ref s)) => Some((s.total_samples as u32 / s.sample_rate) as u32),
_ => None
};
Ok(SongTags {
artist: vorbis.artist().map(|v| v[0].clone()),
album_artist: vorbis.album_artist().map(|v| v[0].clone()),
album: vorbis.album().map(|v| v[0].clone()),
title: vorbis.title().map(|v| v[0].clone()),
duration: duration,
disc_number: disc_number,
track_number: vorbis.track(),
year: year,
})
}
#[test]
fn test_read_metadata() {
let sample_tags = SongTags {
disc_number: Some(3),
track_number: Some(1),
title: Some("TEST TITLE".into()),
artist: Some("TEST ARTIST".into()),
album_artist: Some("TEST ALBUM ARTIST".into()),
album: Some("TEST ALBUM".into()),
duration: None, | let mp3_sample_tag = SongTags {duration: Some(0), ..sample_tags.clone()};
assert_eq!(read(Path::new("test/sample.mp3")).unwrap(), mp3_sample_tag);
assert_eq!(read(Path::new("test/sample.ogg")).unwrap(), sample_tags);
assert_eq!(read(Path::new("test/sample.flac")).unwrap(), flac_sample_tag);
} | year: Some(2016),
};
let flac_sample_tag = SongTags {duration: Some(0), ..sample_tags.clone()}; | random_line_split |
metadata.rs | use ape;
use id3;
use lewton::inside_ogg::OggStreamReader;
use metaflac;
use mp3_duration;
use regex::Regex;
use std::fs;
use std::path::Path;
use errors::*;
use utils;
use utils::AudioFormat;
#[derive(Debug, Clone, PartialEq)]
pub struct SongTags {
pub disc_number: Option<u32>,
pub track_number: Option<u32>,
pub title: Option<String>,
pub duration: Option<u32>,
pub artist: Option<String>,
pub album_artist: Option<String>,
pub album: Option<String>,
pub year: Option<i32>,
}
pub fn read(path: &Path) -> Result<SongTags> {
match utils::get_audio_format(path) {
Some(AudioFormat::FLAC) => read_flac(path),
Some(AudioFormat::MP3) => read_id3(path),
Some(AudioFormat::MPC) => read_ape(path),
Some(AudioFormat::OGG) => read_vorbis(path),
_ => bail!("Unsupported file format for reading metadata"),
}
}
fn read_id3(path: &Path) -> Result<SongTags> {
let tag = id3::Tag::read_from_path(&path)?;
let duration = mp3_duration::from_path(&path).map(|d| d.as_secs() as u32).ok();
let artist = tag.artist().map(|s| s.to_string());
let album_artist = tag.album_artist().map(|s| s.to_string());
let album = tag.album().map(|s| s.to_string());
let title = tag.title().map(|s| s.to_string());
let disc_number = tag.disc();
let track_number = tag.track();
let year = tag.year()
.map(|y| y as i32)
.or(tag.date_released().and_then(|d| Some(d.year)))
.or(tag.date_recorded().and_then(|d| Some(d.year)));
Ok(SongTags {
artist: artist,
album_artist: album_artist,
album: album,
title: title,
duration: duration,
disc_number: disc_number,
track_number: track_number,
year: year,
})
}
fn read_ape_string(item: &ape::Item) -> Option<String> {
match item.value {
ape::ItemValue::Text(ref s) => Some(s.clone()),
_ => None,
}
}
fn read_ape_i32(item: &ape::Item) -> Option<i32> {
match item.value {
ape::ItemValue::Text(ref s) => s.parse::<i32>().ok(),
_ => None,
}
}
fn read_ape_x_of_y(item: &ape::Item) -> Option<u32> {
match item.value {
ape::ItemValue::Text(ref s) => {
let format = Regex::new(r#"^\d+"#).unwrap();
if let Some(m) = format.find(s) {
s[m.start()..m.end()].parse().ok()
} else {
None
}
}
_ => None,
}
}
fn read_ape(path: &Path) -> Result<SongTags> {
let tag = ape::read(path)?;
let artist = tag.item("Artist").and_then(read_ape_string);
let album = tag.item("Album").and_then(read_ape_string);
let album_artist = tag.item("Album artist").and_then(read_ape_string);
let title = tag.item("Title").and_then(read_ape_string);
let year = tag.item("Year").and_then(read_ape_i32);
let disc_number = tag.item("Disc").and_then(read_ape_x_of_y);
let track_number = tag.item("Track").and_then(read_ape_x_of_y);
Ok(SongTags {
artist: artist,
album_artist: album_artist,
album: album,
title: title,
duration: None,
disc_number: disc_number,
track_number: track_number,
year: year,
})
}
fn read_vorbis(path: &Path) -> Result<SongTags> {
let file = fs::File::open(path)?;
let source = OggStreamReader::new(file)?;
let mut tags = SongTags {
artist: None,
album_artist: None,
album: None,
title: None,
duration:None,
disc_number: None,
track_number: None,
year: None,
};
for (key, value) in source.comment_hdr.comment_list {
match key.as_str() {
"TITLE" => tags.title = Some(value),
"ALBUM" => tags.album = Some(value),
"ARTIST" => tags.artist = Some(value),
"ALBUMARTIST" => tags.album_artist = Some(value),
"TRACKNUMBER" => tags.track_number = value.parse::<u32>().ok(),
"DISCNUMBER" => tags.disc_number = value.parse::<u32>().ok(),
"DATE" => tags.year = value.parse::<i32>().ok(),
_ => (),
}
}
Ok(tags)
}
fn | (path: &Path) -> Result<SongTags> {
let tag = metaflac::Tag::read_from_path(path)?;
let vorbis = tag.vorbis_comments().ok_or("Missing Vorbis comments")?;
let disc_number = vorbis
.get("DISCNUMBER")
.and_then(|d| d[0].parse::<u32>().ok());
let year = vorbis.get("DATE").and_then(|d| d[0].parse::<i32>().ok());
let streaminfo = tag.get_blocks(metaflac::BlockType::StreamInfo);
let duration = match streaminfo.first() {
Some(&&metaflac::Block::StreamInfo(ref s)) => Some((s.total_samples as u32 / s.sample_rate) as u32),
_ => None
};
Ok(SongTags {
artist: vorbis.artist().map(|v| v[0].clone()),
album_artist: vorbis.album_artist().map(|v| v[0].clone()),
album: vorbis.album().map(|v| v[0].clone()),
title: vorbis.title().map(|v| v[0].clone()),
duration: duration,
disc_number: disc_number,
track_number: vorbis.track(),
year: year,
})
}
#[test]
fn test_read_metadata() {
let sample_tags = SongTags {
disc_number: Some(3),
track_number: Some(1),
title: Some("TEST TITLE".into()),
artist: Some("TEST ARTIST".into()),
album_artist: Some("TEST ALBUM ARTIST".into()),
album: Some("TEST ALBUM".into()),
duration: None,
year: Some(2016),
};
let flac_sample_tag = SongTags {duration: Some(0), ..sample_tags.clone()};
let mp3_sample_tag = SongTags {duration: Some(0), ..sample_tags.clone()};
assert_eq!(read(Path::new("test/sample.mp3")).unwrap(), mp3_sample_tag);
assert_eq!(read(Path::new("test/sample.ogg")).unwrap(), sample_tags);
assert_eq!(read(Path::new("test/sample.flac")).unwrap(), flac_sample_tag);
}
| read_flac | identifier_name |
metadata.rs | use ape;
use id3;
use lewton::inside_ogg::OggStreamReader;
use metaflac;
use mp3_duration;
use regex::Regex;
use std::fs;
use std::path::Path;
use errors::*;
use utils;
use utils::AudioFormat;
#[derive(Debug, Clone, PartialEq)]
pub struct SongTags {
pub disc_number: Option<u32>,
pub track_number: Option<u32>,
pub title: Option<String>,
pub duration: Option<u32>,
pub artist: Option<String>,
pub album_artist: Option<String>,
pub album: Option<String>,
pub year: Option<i32>,
}
pub fn read(path: &Path) -> Result<SongTags> {
match utils::get_audio_format(path) {
Some(AudioFormat::FLAC) => read_flac(path),
Some(AudioFormat::MP3) => read_id3(path),
Some(AudioFormat::MPC) => read_ape(path),
Some(AudioFormat::OGG) => read_vorbis(path),
_ => bail!("Unsupported file format for reading metadata"),
}
}
fn read_id3(path: &Path) -> Result<SongTags> {
let tag = id3::Tag::read_from_path(&path)?;
let duration = mp3_duration::from_path(&path).map(|d| d.as_secs() as u32).ok();
let artist = tag.artist().map(|s| s.to_string());
let album_artist = tag.album_artist().map(|s| s.to_string());
let album = tag.album().map(|s| s.to_string());
let title = tag.title().map(|s| s.to_string());
let disc_number = tag.disc();
let track_number = tag.track();
let year = tag.year()
.map(|y| y as i32)
.or(tag.date_released().and_then(|d| Some(d.year)))
.or(tag.date_recorded().and_then(|d| Some(d.year)));
Ok(SongTags {
artist: artist,
album_artist: album_artist,
album: album,
title: title,
duration: duration,
disc_number: disc_number,
track_number: track_number,
year: year,
})
}
fn read_ape_string(item: &ape::Item) -> Option<String> {
match item.value {
ape::ItemValue::Text(ref s) => Some(s.clone()),
_ => None,
}
}
fn read_ape_i32(item: &ape::Item) -> Option<i32> {
match item.value {
ape::ItemValue::Text(ref s) => s.parse::<i32>().ok(),
_ => None,
}
}
fn read_ape_x_of_y(item: &ape::Item) -> Option<u32> |
fn read_ape(path: &Path) -> Result<SongTags> {
let tag = ape::read(path)?;
let artist = tag.item("Artist").and_then(read_ape_string);
let album = tag.item("Album").and_then(read_ape_string);
let album_artist = tag.item("Album artist").and_then(read_ape_string);
let title = tag.item("Title").and_then(read_ape_string);
let year = tag.item("Year").and_then(read_ape_i32);
let disc_number = tag.item("Disc").and_then(read_ape_x_of_y);
let track_number = tag.item("Track").and_then(read_ape_x_of_y);
Ok(SongTags {
artist: artist,
album_artist: album_artist,
album: album,
title: title,
duration: None,
disc_number: disc_number,
track_number: track_number,
year: year,
})
}
fn read_vorbis(path: &Path) -> Result<SongTags> {
let file = fs::File::open(path)?;
let source = OggStreamReader::new(file)?;
let mut tags = SongTags {
artist: None,
album_artist: None,
album: None,
title: None,
duration:None,
disc_number: None,
track_number: None,
year: None,
};
for (key, value) in source.comment_hdr.comment_list {
match key.as_str() {
"TITLE" => tags.title = Some(value),
"ALBUM" => tags.album = Some(value),
"ARTIST" => tags.artist = Some(value),
"ALBUMARTIST" => tags.album_artist = Some(value),
"TRACKNUMBER" => tags.track_number = value.parse::<u32>().ok(),
"DISCNUMBER" => tags.disc_number = value.parse::<u32>().ok(),
"DATE" => tags.year = value.parse::<i32>().ok(),
_ => (),
}
}
Ok(tags)
}
fn read_flac(path: &Path) -> Result<SongTags> {
let tag = metaflac::Tag::read_from_path(path)?;
let vorbis = tag.vorbis_comments().ok_or("Missing Vorbis comments")?;
let disc_number = vorbis
.get("DISCNUMBER")
.and_then(|d| d[0].parse::<u32>().ok());
let year = vorbis.get("DATE").and_then(|d| d[0].parse::<i32>().ok());
let streaminfo = tag.get_blocks(metaflac::BlockType::StreamInfo);
let duration = match streaminfo.first() {
Some(&&metaflac::Block::StreamInfo(ref s)) => Some((s.total_samples as u32 / s.sample_rate) as u32),
_ => None
};
Ok(SongTags {
artist: vorbis.artist().map(|v| v[0].clone()),
album_artist: vorbis.album_artist().map(|v| v[0].clone()),
album: vorbis.album().map(|v| v[0].clone()),
title: vorbis.title().map(|v| v[0].clone()),
duration: duration,
disc_number: disc_number,
track_number: vorbis.track(),
year: year,
})
}
#[test]
fn test_read_metadata() {
let sample_tags = SongTags {
disc_number: Some(3),
track_number: Some(1),
title: Some("TEST TITLE".into()),
artist: Some("TEST ARTIST".into()),
album_artist: Some("TEST ALBUM ARTIST".into()),
album: Some("TEST ALBUM".into()),
duration: None,
year: Some(2016),
};
let flac_sample_tag = SongTags {duration: Some(0), ..sample_tags.clone()};
let mp3_sample_tag = SongTags {duration: Some(0), ..sample_tags.clone()};
assert_eq!(read(Path::new("test/sample.mp3")).unwrap(), mp3_sample_tag);
assert_eq!(read(Path::new("test/sample.ogg")).unwrap(), sample_tags);
assert_eq!(read(Path::new("test/sample.flac")).unwrap(), flac_sample_tag);
}
| {
match item.value {
ape::ItemValue::Text(ref s) => {
let format = Regex::new(r#"^\d+"#).unwrap();
if let Some(m) = format.find(s) {
s[m.start()..m.end()].parse().ok()
} else {
None
}
}
_ => None,
}
} | identifier_body |
urls.py | from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
admin.autodiscover()
import views
urlpatterns = patterns('',
url(r'^pis', views.pis),
url(r'^words', views.words, { 'titles': False }),
url(r'^projects', views.projects),
url(r'^posters', views.posters),
url(r'^posterpresenters', views.posterpresenters),
url(r'^pigraph', views.pigraph),
url(r'^institutions', views.institutions),
url(r'^institution/(?P<institutionid>\d+)', views.institution),
url(r'^profile/$', views.profile),
url(r'^schedule/(?P<email>\S+)', views.schedule),
url(r'^ratemeeting/(?P<rmid>\d+)/(?P<email>\S+)', views.ratemeeting),
url(r'^submitrating/(?P<rmid>\d+)/(?P<email>\S+)', views.submitrating),
url(r'^feedback/(?P<email>\S+)', views.after),
url(r'^breakouts', views.breakouts),
url(r'^breakout/(?P<bid>\d+)', views.breakout),
url(r'^about', views.about),
url(r'^buginfo', views.buginfo),
url(r'^allrms', views.allrms),
url(r'^allratings', views.allratings),
url(r'^login', views.login),
url(r'^logout', views.logout),
url(r'^edit_home_page', views.edit_home_page),
url(r'^pi/(?P<userid>\d+)', views.pi), # , name = 'pi'),
url(r'^pi/(?P<email>\S+)', views.piEmail), # , name = 'pi'),
url(r'^project/(?P<abstractid>\S+)', views.project, name = 'project'),
url(r'^scope=(?P<scope>\w+)/(?P<url>.+)$', views.set_scope),
url(r'^active=(?P<active>\d)/(?P<url>.+)$', views.set_active),
url(r'^admin/', include(admin.site.urls)),
(r'', include('django_browserid.urls')), | url(r'^$', views.index, name = 'index'),
) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) | random_line_split | |
app.rs | use clap::{App, Arg};
const DEFAULT_RETRY_INTERVAL: &str = "1000";
const DEFAULT_UPDATE_INTERVAL: &str = "1000";
const DEFAULT_CALCULATION_THREADS: &str = "1";
const DEFAULT_CALCULATION_LIMIT: &str = "1000";
const DEFAULT_GENERATION_LIMIT: &str = "10";
const DEFAULT_MILESTONE_ADDRESS: &str =
"KPWCHICGJZXKE9GSUDXZYUAPLHAKAHYHDXNPHENTE\
RYMMBQOPSQIDENXKLKCEYCPVTZQLEEJVYJZV9BWU";
const DEFAULT_MILESTONE_START_INDEX: &str = "62000";
const DEFAULT_LOG_CONFIG: &str = "log4rs.yaml";
pub fn build<'a, 'b>() -> App<'a, 'b> | {
app_from_crate!()
.arg(
Arg::with_name("zmq_uri")
.short("z")
.long("zmq")
.takes_value(true)
.value_name("URI")
.required(true)
.help("ZMQ source server URI"),
)
.arg(
Arg::with_name("mysql_uri")
.short("m")
.long("mysql")
.takes_value(true)
.value_name("URI")
.required(true)
.help("MySQL destination server URI"),
)
.arg(
Arg::with_name("retry_interval")
.short("r")
.long("retry-interval")
.takes_value(true)
.value_name("INTERVAL")
.default_value(DEFAULT_RETRY_INTERVAL)
.help("MySQL connect retry interval in milliseconds"),
)
.arg(
Arg::with_name("update_interval")
.short("u")
.long("update-interval")
.takes_value(true)
.value_name("INTERVAL")
.default_value(DEFAULT_UPDATE_INTERVAL)
.help("MySQL update interval in milliseconds"),
)
.arg(
Arg::with_name("calculation_threads")
.short("T")
.long("calculation-threads")
.takes_value(true)
.value_name("THREADS")
.default_value(DEFAULT_CALCULATION_THREADS)
.help("Number of calculation threads"),
)
.arg(
Arg::with_name("calculation_limit")
.short("t")
.long("calculation-limit")
.takes_value(true)
.value_name("LIMIT")
.default_value(DEFAULT_CALCULATION_LIMIT)
.help("Calculation depth limit"),
)
.arg(
Arg::with_name("generation_limit")
.short("g")
.long("generation-limit")
.takes_value(true)
.value_name("LIMIT")
.default_value(DEFAULT_GENERATION_LIMIT)
.help("Garbage collector generation limit"),
)
.arg(
Arg::with_name("milestone_address")
.short("M")
.long("milestone-address")
.takes_value(true)
.value_name("ADDRESS")
.default_value(DEFAULT_MILESTONE_ADDRESS)
.help("Milestone address"),
)
.arg(
Arg::with_name("milestone_start_index")
.short("I")
.long("milestone-start-index")
.takes_value(true)
.value_name("INDEX")
.default_value(DEFAULT_MILESTONE_START_INDEX)
.help("Milestone start index"),
)
.arg(
Arg::with_name("log_config")
.short("C")
.long("log-config")
.takes_value(true)
.value_name("FILE")
.default_value(DEFAULT_LOG_CONFIG)
.help("Path to log4rs configuration file"),
)
} | identifier_body | |
app.rs | use clap::{App, Arg};
const DEFAULT_RETRY_INTERVAL: &str = "1000";
const DEFAULT_UPDATE_INTERVAL: &str = "1000";
const DEFAULT_CALCULATION_THREADS: &str = "1";
const DEFAULT_CALCULATION_LIMIT: &str = "1000";
const DEFAULT_GENERATION_LIMIT: &str = "10";
const DEFAULT_MILESTONE_ADDRESS: &str =
"KPWCHICGJZXKE9GSUDXZYUAPLHAKAHYHDXNPHENTE\
RYMMBQOPSQIDENXKLKCEYCPVTZQLEEJVYJZV9BWU";
const DEFAULT_MILESTONE_START_INDEX: &str = "62000";
const DEFAULT_LOG_CONFIG: &str = "log4rs.yaml";
pub fn | <'a, 'b>() -> App<'a, 'b> {
app_from_crate!()
.arg(
Arg::with_name("zmq_uri")
.short("z")
.long("zmq")
.takes_value(true)
.value_name("URI")
.required(true)
.help("ZMQ source server URI"),
)
.arg(
Arg::with_name("mysql_uri")
.short("m")
.long("mysql")
.takes_value(true)
.value_name("URI")
.required(true)
.help("MySQL destination server URI"),
)
.arg(
Arg::with_name("retry_interval")
.short("r")
.long("retry-interval")
.takes_value(true)
.value_name("INTERVAL")
.default_value(DEFAULT_RETRY_INTERVAL)
.help("MySQL connect retry interval in milliseconds"),
)
.arg(
Arg::with_name("update_interval")
.short("u")
.long("update-interval")
.takes_value(true)
.value_name("INTERVAL")
.default_value(DEFAULT_UPDATE_INTERVAL)
.help("MySQL update interval in milliseconds"),
)
.arg(
Arg::with_name("calculation_threads")
.short("T")
.long("calculation-threads")
.takes_value(true)
.value_name("THREADS")
.default_value(DEFAULT_CALCULATION_THREADS)
.help("Number of calculation threads"),
)
.arg(
Arg::with_name("calculation_limit")
.short("t")
.long("calculation-limit")
.takes_value(true)
.value_name("LIMIT")
.default_value(DEFAULT_CALCULATION_LIMIT)
.help("Calculation depth limit"),
)
.arg(
Arg::with_name("generation_limit")
.short("g")
.long("generation-limit")
.takes_value(true)
.value_name("LIMIT")
.default_value(DEFAULT_GENERATION_LIMIT)
.help("Garbage collector generation limit"),
)
.arg(
Arg::with_name("milestone_address")
.short("M")
.long("milestone-address")
.takes_value(true)
.value_name("ADDRESS")
.default_value(DEFAULT_MILESTONE_ADDRESS)
.help("Milestone address"),
)
.arg(
Arg::with_name("milestone_start_index")
.short("I")
.long("milestone-start-index")
.takes_value(true)
.value_name("INDEX")
.default_value(DEFAULT_MILESTONE_START_INDEX)
.help("Milestone start index"),
)
.arg(
Arg::with_name("log_config")
.short("C")
.long("log-config")
.takes_value(true)
.value_name("FILE")
.default_value(DEFAULT_LOG_CONFIG)
.help("Path to log4rs configuration file"),
)
}
| build | identifier_name |
app.rs | use clap::{App, Arg};
const DEFAULT_RETRY_INTERVAL: &str = "1000";
const DEFAULT_UPDATE_INTERVAL: &str = "1000";
const DEFAULT_CALCULATION_THREADS: &str = "1";
const DEFAULT_CALCULATION_LIMIT: &str = "1000";
const DEFAULT_GENERATION_LIMIT: &str = "10";
const DEFAULT_MILESTONE_ADDRESS: &str =
"KPWCHICGJZXKE9GSUDXZYUAPLHAKAHYHDXNPHENTE\
RYMMBQOPSQIDENXKLKCEYCPVTZQLEEJVYJZV9BWU";
const DEFAULT_MILESTONE_START_INDEX: &str = "62000";
const DEFAULT_LOG_CONFIG: &str = "log4rs.yaml";
pub fn build<'a, 'b>() -> App<'a, 'b> {
app_from_crate!()
.arg(
Arg::with_name("zmq_uri")
.short("z")
.long("zmq")
.takes_value(true) | .help("ZMQ source server URI"),
)
.arg(
Arg::with_name("mysql_uri")
.short("m")
.long("mysql")
.takes_value(true)
.value_name("URI")
.required(true)
.help("MySQL destination server URI"),
)
.arg(
Arg::with_name("retry_interval")
.short("r")
.long("retry-interval")
.takes_value(true)
.value_name("INTERVAL")
.default_value(DEFAULT_RETRY_INTERVAL)
.help("MySQL connect retry interval in milliseconds"),
)
.arg(
Arg::with_name("update_interval")
.short("u")
.long("update-interval")
.takes_value(true)
.value_name("INTERVAL")
.default_value(DEFAULT_UPDATE_INTERVAL)
.help("MySQL update interval in milliseconds"),
)
.arg(
Arg::with_name("calculation_threads")
.short("T")
.long("calculation-threads")
.takes_value(true)
.value_name("THREADS")
.default_value(DEFAULT_CALCULATION_THREADS)
.help("Number of calculation threads"),
)
.arg(
Arg::with_name("calculation_limit")
.short("t")
.long("calculation-limit")
.takes_value(true)
.value_name("LIMIT")
.default_value(DEFAULT_CALCULATION_LIMIT)
.help("Calculation depth limit"),
)
.arg(
Arg::with_name("generation_limit")
.short("g")
.long("generation-limit")
.takes_value(true)
.value_name("LIMIT")
.default_value(DEFAULT_GENERATION_LIMIT)
.help("Garbage collector generation limit"),
)
.arg(
Arg::with_name("milestone_address")
.short("M")
.long("milestone-address")
.takes_value(true)
.value_name("ADDRESS")
.default_value(DEFAULT_MILESTONE_ADDRESS)
.help("Milestone address"),
)
.arg(
Arg::with_name("milestone_start_index")
.short("I")
.long("milestone-start-index")
.takes_value(true)
.value_name("INDEX")
.default_value(DEFAULT_MILESTONE_START_INDEX)
.help("Milestone start index"),
)
.arg(
Arg::with_name("log_config")
.short("C")
.long("log-config")
.takes_value(true)
.value_name("FILE")
.default_value(DEFAULT_LOG_CONFIG)
.help("Path to log4rs configuration file"),
)
} | .value_name("URI")
.required(true) | random_line_split |
example-repositories.js | export const EXAMPLE_REPOSITORIES = {
clock: { repo: 'https://github.com/meteor/clock' },
leaderboard: { repo: 'https://github.com/meteor/leaderboard' },
localmarket: { repo: 'https://github.com/meteor/localmarket' },
'simple-todos': { repo: 'https://github.com/meteor/simple-todos' },
'simple-todos-react': {
repo: 'https://github.com/meteor/simple-todos-react'
},
'simple-todos-angular': {
repo: 'https://github.com/meteor/simple-todos-angular'
},
todos: { repo: 'https://github.com/meteor/todos' },
'todos-react': {
'repo': 'https://github.com/meteor/todos',
'branch': 'react', | }
}; | },
'angular2-boilerplate': {
repo: 'https://github.com/bsliran/angular2-meteor-base' | random_line_split |
jvmcfg.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2014 Glencoe Software, Inc. All Rights Reserved.
# Use is subject to license terms supplied in LICENSE.txt
#
# 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.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""
Automatic configuration of memory settings for Java servers.
"""
from types import StringType
from shlex import split
import logging
LOGGER = logging.getLogger("omero.install.jvmcfg")
def strip_dict(map, prefix=("omero", "jvmcfg"), suffix=(), limit=1):
"""
For the given dictionary, return a copy of the
dictionary where all entries not matching the
prefix, suffix, and limit have been removed and
where all remaining keys have had the prefix and
suffix stripped. The limit describes the number
of elements that are allowed in the new key after
stripping prefix and suffix.
"""
if isinstance(prefix, StringType):
prefix = tuple(prefix.split("."))
if isinstance(suffix, StringType):
suffix = tuple(suffix.split("."))
rv = dict()
if not map:
return dict()
def __strip_dict(k, v, prefix, suffix, rv):
key = tuple(k.split("."))
ksz = len(key)
psz = len(prefix)
ssz = len(suffix)
if ksz <= (psz + ssz):
return # No way to strip if smaller
if key[0:psz] == prefix and key[ksz-ssz:] == suffix:
newkey = key[psz:ksz-ssz]
if len(newkey) == limit:
newkey = ".".join(newkey)
rv[newkey] = v
for k, v in map.items():
__strip_dict(k, v, prefix, suffix, rv)
return rv
class StrategyRegistry(dict):
def __init__(self, *args, **kwargs):
super(dict, self).__init__(*args, **kwargs)
STRATEGY_REGISTRY = StrategyRegistry()
class Settings(object):
"""
Container for the config options found in etc/grid/config.xml
"""
def __init__(self, server_values=None, global_values=None):
if server_values is None:
self.__server = dict()
else:
self.__server = server_values
if global_values is None:
self.__global = dict()
else:
self.__global = global_values
self.__static = {
"strategy": PercentStrategy,
"append": "",
"perm_gen": "128m",
"heap_dump": "off",
"heap_size": "512m",
"system_memory": None,
"max_system_memory": "48000",
"min_system_memory": "3414",
}
self.__manual = dict()
def __getattr__(self, key):
return self.lookup(key)
def lookup(self, key, default=None):
if key in self.__manual:
return self.__manual[key]
elif key in self.__server:
return self.__server[key]
elif key in self.__global:
return self.__global[key]
elif key in self.__static:
return self.__static[key]
else:
return default
def overwrite(self, key, value, always=False):
if self.was_set(key) and not always:
# Then we leave it as the user requested
return
else:
self.__manual[key] = value
def was_set(self, key):
return key in self.__server or key in self.__global
def get_strategy(self):
return STRATEGY_REGISTRY.get(self.strategy, self.strategy)
def __str__(self):
rv = dict()
rv.update(self.__server)
rv.update(self.__global)
if not rv:
rv = ""
return 'Settings(%s)' % rv
class Strategy(object):
"""
Strategy for calculating memory settings. Primary
class of the memory module.
"""
def __init__(self, name, settings=None):
"""
'name' argument should likely be one of:
('blitz', 'indexer', 'pixeldata', 'repository')
"""
if settings is None:
settings = Settings()
self.name = name
self.settings = settings
if type(self) == Strategy:
raise Exception("Must subclass!")
# Memory helpers
def system_memory_mb(self):
"""
Returns a tuple, in MB, of available, active, and total memory.
"total" memory is found by calling to first a Python library
(if installed) and otherwise a Java class. If
"system_memory" is set, it will short-circuit both methods.
"active" memory is set to "total" but limited by "min_system_memory"
and "max_system_memory".
"available" may not be accurate, and in some cases will be
set to total.
"""
available, total = None, None
if self.settings.system_memory is not None:
total = int(self.settings.system_memory)
available = total
else:
pymem = self._system_memory_mb_psutil()
if pymem is not None:
available, total = pymem
else:
available, total = self._system_memory_mb_java()
max_system_memory = int(self.settings.max_system_memory)
min_system_memory = int(self.settings.min_system_memory)
active = max(min(total, max_system_memory), min_system_memory)
return available, active, total
def _system_memory_mb_psutil(self):
try:
import psutil
pymem = psutil.virtual_memory()
return (pymem.free/1000000, pymem.total/1000000)
except ImportError:
LOGGER.debug("No psutil installed")
return None
def _system_memory_mb_java(self):
import omero.cli
import omero.java
# Copied from db.py. Needs better dir detection
cwd = omero.cli.CLI().dir
server_jar = cwd / "lib" / "server" / "server.jar"
cmd = ["ome.services.util.JvmSettingsCheck", "--psutil"]
p = omero.java.popen(["-cp", str(server_jar)] + cmd)
o, e = p.communicate()
if p.poll() != 0:
LOGGER.warn("Failed to invoke java:\nout:%s\nerr:%s",
o, e)
rv = dict()
for line in o.split("\n"):
line = line.strip()
if not line:
continue
parts = line.split(":")
if len(parts) == 1:
parts.append("")
rv[parts[0]] = parts[1]
try:
free = long(rv["Free"]) / 1000000
except:
LOGGER.warn("Failed to parse Free from %s", rv)
free = 2000
try:
total = long(rv["Total"]) / 1000000
except:
LOGGER.warn("Failed to parse Total from %s", rv)
total = 4000
return (free, total)
# API Getters
def get_heap_size(self, sz=None):
if sz is None or self.settings.was_set("heap_size"):
sz = self.settings.heap_size
if str(sz).startswith("-X"):
return sz
else:
rv = "-Xmx%s" % sz
if rv[-1].lower() not in ("b", "k", "m", "g"):
rv = "%sm" % rv
return rv
def get_heap_dump(self):
hd = self.settings.heap_dump
if hd == "off":
return ""
elif hd in ("on", "cwd", "tmp"):
return "-XX:+HeapDumpOnOutOfMemoryError"
def get_perm_gen(self):
pg = self.settings.perm_gen
if str(pg).startswith("-XX"):
return pg
else:
return "-XX:MaxPermSize=%s" % pg
def get_append(self):
values = []
if self.settings.heap_dump == "tmp":
import tempfile
tmp = tempfile.gettempdir()
values.append("-XX:HeapDumpPath=%s" % tmp)
return values + split(self.settings.append)
def | (self):
values = [
self.get_heap_size(),
self.get_heap_dump(),
self.get_perm_gen(),
]
if any([x.startswith("-XX:MaxPermSize") for x in values]):
values.append("-XX:+IgnoreUnrecognizedVMOptions")
values += self.get_append()
return [x for x in values if x]
class ManualStrategy(Strategy):
"""
Simplest strategy which assumes all values have
been set and simply uses them or their defaults.
"""
class PercentStrategy(Strategy):
"""
Strategy based on a percent of available memory.
"""
PERCENT_DEFAULTS = (
("blitz", 15),
("pixeldata", 15),
("indexer", 10),
("repository", 10),
("other", 1),
)
def __init__(self, name, settings=None):
super(PercentStrategy, self).__init__(name, settings)
self.defaults = dict(self.PERCENT_DEFAULTS)
self.use_active = True
def get_heap_size(self):
"""
Uses the results of the default settings of
calculate_heap_size() as an argument to
get_heap_size(), in other words some percent
of the active memory.
"""
sz = self.calculate_heap_size()
return super(PercentStrategy, self).get_heap_size(sz)
def get_percent(self):
other = self.defaults.get("other", "1")
default = self.defaults.get(self.name, other)
percent = int(self.settings.lookup("percent", default))
return percent
def get_perm_gen(self):
available, active, total = self.system_memory_mb()
choice = self.use_active and active or total
if choice <= 4000:
if choice >= 2000:
self.settings.overwrite("perm_gen", "256m")
elif choice <= 8000:
self.settings.overwrite("perm_gen", "512m")
else:
self.settings.overwrite("perm_gen", "1g")
return super(PercentStrategy, self).get_perm_gen()
def calculate_heap_size(self, method=None):
"""
Re-calculates the appropriate heap size based on the
value of get_percent(). The "active" memory returned
by method() will be used by default, but can be modified
to use "total" via the "use_active" flag.
"""
if method is None:
method = self.system_memory_mb
available, active, total = method()
choice = self.use_active and active or total
percent = self.get_percent()
calculated = choice * int(percent) / 100
return calculated
def usage_table(self, min=10, max=20):
total_mb = [2**x for x in range(min, max)]
for total in total_mb:
method = lambda: (total, total, total)
yield total, self.calculate_heap_size(method)
STRATEGY_REGISTRY["manual"] = ManualStrategy
STRATEGY_REGISTRY["percent"] = PercentStrategy
def adjust_settings(config, template_xml,
blitz=None, indexer=None,
pixeldata=None, repository=None):
"""
Takes an omero.config.ConfigXml object and adjusts
the memory settings. Primary entry point to the
memory module.
"""
from xml.etree.ElementTree import Element
from collections import defaultdict
replacements = dict()
options = dict()
for template in template_xml.findall("server-template"):
for server in template.findall("server"):
for option in server.findall("option"):
o = option.text
if o.startswith("MEMORY:"):
options[o[7:]] = (server, option)
for props in server.findall("properties"):
for prop in props.findall("property"):
name = prop.attrib.get("name", "")
if name.startswith("REPLACEMENT:"):
replacements[name[12:]] = (server, prop)
rv = defaultdict(list)
m = config.as_map()
loop = (("blitz", blitz), ("indexer", indexer),
("pixeldata", pixeldata), ("repository", repository))
for name, StrategyType in loop:
if name not in options:
raise Exception(
"Cannot find %s option. Make sure templates.xml was "
"not copied from an older server" % name)
for name, StrategyType in loop:
specific = strip_dict(m, suffix=name)
defaults = strip_dict(m)
settings = Settings(specific, defaults)
rv[name].append(settings)
if StrategyType is None:
StrategyType = settings.get_strategy()
if not callable(StrategyType):
raise Exception("Bad strategy: %s" % StrategyType)
strategy = StrategyType(name, settings)
settings = strategy.get_memory_settings()
server, option = options[name]
idx = 0
for v in settings:
rv[name].append(v)
if idx == 0:
option.text = v
else:
elem = Element("option")
elem.text = v
server.insert(idx, elem)
idx += 1
# Now we check for any other properties and
# put them where the replacement should go.
for k, v in m.items():
r = []
suffix = ".%s" % name
size = len(suffix)
if k.endswith(suffix):
k = k[:-size]
r.append((k, v))
server, replacement = replacements[name]
idx = 0
for k, v in r:
if idx == 0:
replacement.attrib["name"] = k
replacement.attrib["value"] = v
else:
elem = Element("property", name=k, value=v)
server.append(elem)
return rv
def usage_charts(path,
min=0, max=20,
Strategy=PercentStrategy, name="blitz"):
# See http://matplotlib.org/examples/pylab_examples/anscombe.html
from pylab import array
from pylab import axis
from pylab import gca
from pylab import subplot
from pylab import plot
from pylab import setp
from pylab import savefig
from pylab import text
points = 200
x = array([2 ** (x / points) / 1000
for x in range(min*points, max*points)])
y_configs = (
(Settings({}), 'A'),
(Settings({"percent": "20"}), 'B'),
(Settings({}), 'C'),
(Settings({"max_system_memory": "10000"}), 'D'),
)
def f(cfg):
s = Strategy(name, settings=cfg[0])
y = []
for total in x:
method = lambda: (total, total, total)
y.append(s.calculate_heap_size(method))
return y
y1 = f(y_configs[0])
y2 = f(y_configs[1])
y3 = f(y_configs[2])
y4 = f(y_configs[3])
axis_values = [0, 20, 0, 6]
def ticks_f():
setp(gca(), xticks=(8, 16), yticks=(2, 4))
def text_f(which):
cfg = y_configs[which]
# s = cfg[0]
txt = "%s" % (cfg[1],)
text(2, 2, txt, fontsize=20)
subplot(221)
plot(x, y1)
axis(axis_values)
text_f(0)
ticks_f()
subplot(222)
plot(x, y2)
axis(axis_values)
text_f(1)
ticks_f()
subplot(223)
plot(x, y3)
axis(axis_values)
text_f(2)
ticks_f()
subplot(224)
plot(x, y4)
axis(axis_values)
text_f(3)
ticks_f()
savefig(path)
| get_memory_settings | identifier_name |
jvmcfg.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2014 Glencoe Software, Inc. All Rights Reserved.
# Use is subject to license terms supplied in LICENSE.txt
#
# 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.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""
Automatic configuration of memory settings for Java servers.
"""
from types import StringType
from shlex import split
import logging
LOGGER = logging.getLogger("omero.install.jvmcfg")
def strip_dict(map, prefix=("omero", "jvmcfg"), suffix=(), limit=1):
"""
For the given dictionary, return a copy of the
dictionary where all entries not matching the
prefix, suffix, and limit have been removed and
where all remaining keys have had the prefix and
suffix stripped. The limit describes the number
of elements that are allowed in the new key after
stripping prefix and suffix.
"""
if isinstance(prefix, StringType):
prefix = tuple(prefix.split("."))
if isinstance(suffix, StringType):
suffix = tuple(suffix.split("."))
rv = dict()
if not map:
return dict()
def __strip_dict(k, v, prefix, suffix, rv):
key = tuple(k.split("."))
ksz = len(key)
psz = len(prefix)
ssz = len(suffix)
if ksz <= (psz + ssz):
return # No way to strip if smaller
if key[0:psz] == prefix and key[ksz-ssz:] == suffix:
newkey = key[psz:ksz-ssz]
if len(newkey) == limit:
newkey = ".".join(newkey)
rv[newkey] = v
for k, v in map.items():
__strip_dict(k, v, prefix, suffix, rv)
return rv
class StrategyRegistry(dict):
def __init__(self, *args, **kwargs):
super(dict, self).__init__(*args, **kwargs)
STRATEGY_REGISTRY = StrategyRegistry()
class Settings(object):
"""
Container for the config options found in etc/grid/config.xml
"""
def __init__(self, server_values=None, global_values=None):
if server_values is None:
self.__server = dict()
else:
self.__server = server_values
if global_values is None:
self.__global = dict()
else:
self.__global = global_values
self.__static = {
"strategy": PercentStrategy,
"append": "",
"perm_gen": "128m",
"heap_dump": "off",
"heap_size": "512m",
"system_memory": None,
"max_system_memory": "48000",
"min_system_memory": "3414",
}
self.__manual = dict()
def __getattr__(self, key):
return self.lookup(key)
def lookup(self, key, default=None):
if key in self.__manual:
return self.__manual[key]
elif key in self.__server:
return self.__server[key]
elif key in self.__global:
return self.__global[key]
elif key in self.__static:
return self.__static[key]
else:
return default
def overwrite(self, key, value, always=False):
if self.was_set(key) and not always:
# Then we leave it as the user requested
return
else:
self.__manual[key] = value
def was_set(self, key):
return key in self.__server or key in self.__global
def get_strategy(self):
return STRATEGY_REGISTRY.get(self.strategy, self.strategy)
def __str__(self):
rv = dict()
rv.update(self.__server)
rv.update(self.__global)
if not rv:
rv = ""
return 'Settings(%s)' % rv
class Strategy(object):
"""
Strategy for calculating memory settings. Primary
class of the memory module.
"""
def __init__(self, name, settings=None):
"""
'name' argument should likely be one of:
('blitz', 'indexer', 'pixeldata', 'repository')
"""
if settings is None:
settings = Settings()
self.name = name
self.settings = settings
if type(self) == Strategy:
raise Exception("Must subclass!")
# Memory helpers
def system_memory_mb(self):
"""
Returns a tuple, in MB, of available, active, and total memory.
"total" memory is found by calling to first a Python library
(if installed) and otherwise a Java class. If
"system_memory" is set, it will short-circuit both methods.
"active" memory is set to "total" but limited by "min_system_memory"
and "max_system_memory".
"available" may not be accurate, and in some cases will be
set to total.
"""
available, total = None, None
if self.settings.system_memory is not None:
total = int(self.settings.system_memory)
available = total
else:
pymem = self._system_memory_mb_psutil()
if pymem is not None:
available, total = pymem
else:
available, total = self._system_memory_mb_java()
max_system_memory = int(self.settings.max_system_memory)
min_system_memory = int(self.settings.min_system_memory)
active = max(min(total, max_system_memory), min_system_memory)
return available, active, total
def _system_memory_mb_psutil(self):
try:
import psutil
pymem = psutil.virtual_memory()
return (pymem.free/1000000, pymem.total/1000000)
except ImportError:
LOGGER.debug("No psutil installed")
return None
def _system_memory_mb_java(self):
import omero.cli
import omero.java
# Copied from db.py. Needs better dir detection
cwd = omero.cli.CLI().dir
server_jar = cwd / "lib" / "server" / "server.jar"
cmd = ["ome.services.util.JvmSettingsCheck", "--psutil"]
p = omero.java.popen(["-cp", str(server_jar)] + cmd)
o, e = p.communicate()
if p.poll() != 0:
LOGGER.warn("Failed to invoke java:\nout:%s\nerr:%s",
o, e)
rv = dict()
for line in o.split("\n"):
line = line.strip()
if not line:
continue
parts = line.split(":")
if len(parts) == 1:
parts.append("")
rv[parts[0]] = parts[1]
try:
free = long(rv["Free"]) / 1000000
except:
LOGGER.warn("Failed to parse Free from %s", rv)
free = 2000
try:
total = long(rv["Total"]) / 1000000
except:
LOGGER.warn("Failed to parse Total from %s", rv)
total = 4000
return (free, total)
# API Getters
def get_heap_size(self, sz=None):
if sz is None or self.settings.was_set("heap_size"):
sz = self.settings.heap_size
if str(sz).startswith("-X"):
return sz
else:
rv = "-Xmx%s" % sz
if rv[-1].lower() not in ("b", "k", "m", "g"):
rv = "%sm" % rv
return rv
def get_heap_dump(self):
hd = self.settings.heap_dump
if hd == "off":
return ""
elif hd in ("on", "cwd", "tmp"):
return "-XX:+HeapDumpOnOutOfMemoryError"
def get_perm_gen(self):
pg = self.settings.perm_gen
if str(pg).startswith("-XX"):
return pg
else:
return "-XX:MaxPermSize=%s" % pg
def get_append(self):
values = []
if self.settings.heap_dump == "tmp":
import tempfile
tmp = tempfile.gettempdir()
values.append("-XX:HeapDumpPath=%s" % tmp)
return values + split(self.settings.append)
def get_memory_settings(self):
values = [
self.get_heap_size(),
self.get_heap_dump(),
self.get_perm_gen(),
]
if any([x.startswith("-XX:MaxPermSize") for x in values]):
values.append("-XX:+IgnoreUnrecognizedVMOptions")
values += self.get_append()
return [x for x in values if x]
class ManualStrategy(Strategy):
"""
Simplest strategy which assumes all values have
been set and simply uses them or their defaults.
"""
class PercentStrategy(Strategy):
"""
Strategy based on a percent of available memory.
"""
PERCENT_DEFAULTS = (
("blitz", 15),
("pixeldata", 15),
("indexer", 10),
("repository", 10),
("other", 1),
)
def __init__(self, name, settings=None):
super(PercentStrategy, self).__init__(name, settings) | Uses the results of the default settings of
calculate_heap_size() as an argument to
get_heap_size(), in other words some percent
of the active memory.
"""
sz = self.calculate_heap_size()
return super(PercentStrategy, self).get_heap_size(sz)
def get_percent(self):
other = self.defaults.get("other", "1")
default = self.defaults.get(self.name, other)
percent = int(self.settings.lookup("percent", default))
return percent
def get_perm_gen(self):
available, active, total = self.system_memory_mb()
choice = self.use_active and active or total
if choice <= 4000:
if choice >= 2000:
self.settings.overwrite("perm_gen", "256m")
elif choice <= 8000:
self.settings.overwrite("perm_gen", "512m")
else:
self.settings.overwrite("perm_gen", "1g")
return super(PercentStrategy, self).get_perm_gen()
def calculate_heap_size(self, method=None):
"""
Re-calculates the appropriate heap size based on the
value of get_percent(). The "active" memory returned
by method() will be used by default, but can be modified
to use "total" via the "use_active" flag.
"""
if method is None:
method = self.system_memory_mb
available, active, total = method()
choice = self.use_active and active or total
percent = self.get_percent()
calculated = choice * int(percent) / 100
return calculated
def usage_table(self, min=10, max=20):
total_mb = [2**x for x in range(min, max)]
for total in total_mb:
method = lambda: (total, total, total)
yield total, self.calculate_heap_size(method)
STRATEGY_REGISTRY["manual"] = ManualStrategy
STRATEGY_REGISTRY["percent"] = PercentStrategy
def adjust_settings(config, template_xml,
blitz=None, indexer=None,
pixeldata=None, repository=None):
"""
Takes an omero.config.ConfigXml object and adjusts
the memory settings. Primary entry point to the
memory module.
"""
from xml.etree.ElementTree import Element
from collections import defaultdict
replacements = dict()
options = dict()
for template in template_xml.findall("server-template"):
for server in template.findall("server"):
for option in server.findall("option"):
o = option.text
if o.startswith("MEMORY:"):
options[o[7:]] = (server, option)
for props in server.findall("properties"):
for prop in props.findall("property"):
name = prop.attrib.get("name", "")
if name.startswith("REPLACEMENT:"):
replacements[name[12:]] = (server, prop)
rv = defaultdict(list)
m = config.as_map()
loop = (("blitz", blitz), ("indexer", indexer),
("pixeldata", pixeldata), ("repository", repository))
for name, StrategyType in loop:
if name not in options:
raise Exception(
"Cannot find %s option. Make sure templates.xml was "
"not copied from an older server" % name)
for name, StrategyType in loop:
specific = strip_dict(m, suffix=name)
defaults = strip_dict(m)
settings = Settings(specific, defaults)
rv[name].append(settings)
if StrategyType is None:
StrategyType = settings.get_strategy()
if not callable(StrategyType):
raise Exception("Bad strategy: %s" % StrategyType)
strategy = StrategyType(name, settings)
settings = strategy.get_memory_settings()
server, option = options[name]
idx = 0
for v in settings:
rv[name].append(v)
if idx == 0:
option.text = v
else:
elem = Element("option")
elem.text = v
server.insert(idx, elem)
idx += 1
# Now we check for any other properties and
# put them where the replacement should go.
for k, v in m.items():
r = []
suffix = ".%s" % name
size = len(suffix)
if k.endswith(suffix):
k = k[:-size]
r.append((k, v))
server, replacement = replacements[name]
idx = 0
for k, v in r:
if idx == 0:
replacement.attrib["name"] = k
replacement.attrib["value"] = v
else:
elem = Element("property", name=k, value=v)
server.append(elem)
return rv
def usage_charts(path,
min=0, max=20,
Strategy=PercentStrategy, name="blitz"):
# See http://matplotlib.org/examples/pylab_examples/anscombe.html
from pylab import array
from pylab import axis
from pylab import gca
from pylab import subplot
from pylab import plot
from pylab import setp
from pylab import savefig
from pylab import text
points = 200
x = array([2 ** (x / points) / 1000
for x in range(min*points, max*points)])
y_configs = (
(Settings({}), 'A'),
(Settings({"percent": "20"}), 'B'),
(Settings({}), 'C'),
(Settings({"max_system_memory": "10000"}), 'D'),
)
def f(cfg):
s = Strategy(name, settings=cfg[0])
y = []
for total in x:
method = lambda: (total, total, total)
y.append(s.calculate_heap_size(method))
return y
y1 = f(y_configs[0])
y2 = f(y_configs[1])
y3 = f(y_configs[2])
y4 = f(y_configs[3])
axis_values = [0, 20, 0, 6]
def ticks_f():
setp(gca(), xticks=(8, 16), yticks=(2, 4))
def text_f(which):
cfg = y_configs[which]
# s = cfg[0]
txt = "%s" % (cfg[1],)
text(2, 2, txt, fontsize=20)
subplot(221)
plot(x, y1)
axis(axis_values)
text_f(0)
ticks_f()
subplot(222)
plot(x, y2)
axis(axis_values)
text_f(1)
ticks_f()
subplot(223)
plot(x, y3)
axis(axis_values)
text_f(2)
ticks_f()
subplot(224)
plot(x, y4)
axis(axis_values)
text_f(3)
ticks_f()
savefig(path) | self.defaults = dict(self.PERCENT_DEFAULTS)
self.use_active = True
def get_heap_size(self):
""" | random_line_split |
jvmcfg.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2014 Glencoe Software, Inc. All Rights Reserved.
# Use is subject to license terms supplied in LICENSE.txt
#
# 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.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""
Automatic configuration of memory settings for Java servers.
"""
from types import StringType
from shlex import split
import logging
LOGGER = logging.getLogger("omero.install.jvmcfg")
def strip_dict(map, prefix=("omero", "jvmcfg"), suffix=(), limit=1):
"""
For the given dictionary, return a copy of the
dictionary where all entries not matching the
prefix, suffix, and limit have been removed and
where all remaining keys have had the prefix and
suffix stripped. The limit describes the number
of elements that are allowed in the new key after
stripping prefix and suffix.
"""
if isinstance(prefix, StringType):
prefix = tuple(prefix.split("."))
if isinstance(suffix, StringType):
suffix = tuple(suffix.split("."))
rv = dict()
if not map:
return dict()
def __strip_dict(k, v, prefix, suffix, rv):
key = tuple(k.split("."))
ksz = len(key)
psz = len(prefix)
ssz = len(suffix)
if ksz <= (psz + ssz):
return # No way to strip if smaller
if key[0:psz] == prefix and key[ksz-ssz:] == suffix:
newkey = key[psz:ksz-ssz]
if len(newkey) == limit:
newkey = ".".join(newkey)
rv[newkey] = v
for k, v in map.items():
__strip_dict(k, v, prefix, suffix, rv)
return rv
class StrategyRegistry(dict):
def __init__(self, *args, **kwargs):
super(dict, self).__init__(*args, **kwargs)
STRATEGY_REGISTRY = StrategyRegistry()
class Settings(object):
"""
Container for the config options found in etc/grid/config.xml
"""
def __init__(self, server_values=None, global_values=None):
if server_values is None:
self.__server = dict()
else:
self.__server = server_values
if global_values is None:
self.__global = dict()
else:
self.__global = global_values
self.__static = {
"strategy": PercentStrategy,
"append": "",
"perm_gen": "128m",
"heap_dump": "off",
"heap_size": "512m",
"system_memory": None,
"max_system_memory": "48000",
"min_system_memory": "3414",
}
self.__manual = dict()
def __getattr__(self, key):
return self.lookup(key)
def lookup(self, key, default=None):
if key in self.__manual:
return self.__manual[key]
elif key in self.__server:
return self.__server[key]
elif key in self.__global:
return self.__global[key]
elif key in self.__static:
return self.__static[key]
else:
return default
def overwrite(self, key, value, always=False):
if self.was_set(key) and not always:
# Then we leave it as the user requested
return
else:
self.__manual[key] = value
def was_set(self, key):
return key in self.__server or key in self.__global
def get_strategy(self):
return STRATEGY_REGISTRY.get(self.strategy, self.strategy)
def __str__(self):
rv = dict()
rv.update(self.__server)
rv.update(self.__global)
if not rv:
rv = ""
return 'Settings(%s)' % rv
class Strategy(object):
"""
Strategy for calculating memory settings. Primary
class of the memory module.
"""
def __init__(self, name, settings=None):
"""
'name' argument should likely be one of:
('blitz', 'indexer', 'pixeldata', 'repository')
"""
if settings is None:
settings = Settings()
self.name = name
self.settings = settings
if type(self) == Strategy:
raise Exception("Must subclass!")
# Memory helpers
def system_memory_mb(self):
"""
Returns a tuple, in MB, of available, active, and total memory.
"total" memory is found by calling to first a Python library
(if installed) and otherwise a Java class. If
"system_memory" is set, it will short-circuit both methods.
"active" memory is set to "total" but limited by "min_system_memory"
and "max_system_memory".
"available" may not be accurate, and in some cases will be
set to total.
"""
available, total = None, None
if self.settings.system_memory is not None:
total = int(self.settings.system_memory)
available = total
else:
pymem = self._system_memory_mb_psutil()
if pymem is not None:
available, total = pymem
else:
available, total = self._system_memory_mb_java()
max_system_memory = int(self.settings.max_system_memory)
min_system_memory = int(self.settings.min_system_memory)
active = max(min(total, max_system_memory), min_system_memory)
return available, active, total
def _system_memory_mb_psutil(self):
try:
import psutil
pymem = psutil.virtual_memory()
return (pymem.free/1000000, pymem.total/1000000)
except ImportError:
LOGGER.debug("No psutil installed")
return None
def _system_memory_mb_java(self):
import omero.cli
import omero.java
# Copied from db.py. Needs better dir detection
cwd = omero.cli.CLI().dir
server_jar = cwd / "lib" / "server" / "server.jar"
cmd = ["ome.services.util.JvmSettingsCheck", "--psutil"]
p = omero.java.popen(["-cp", str(server_jar)] + cmd)
o, e = p.communicate()
if p.poll() != 0:
LOGGER.warn("Failed to invoke java:\nout:%s\nerr:%s",
o, e)
rv = dict()
for line in o.split("\n"):
line = line.strip()
if not line:
continue
parts = line.split(":")
if len(parts) == 1:
parts.append("")
rv[parts[0]] = parts[1]
try:
free = long(rv["Free"]) / 1000000
except:
LOGGER.warn("Failed to parse Free from %s", rv)
free = 2000
try:
total = long(rv["Total"]) / 1000000
except:
LOGGER.warn("Failed to parse Total from %s", rv)
total = 4000
return (free, total)
# API Getters
def get_heap_size(self, sz=None):
|
def get_heap_dump(self):
hd = self.settings.heap_dump
if hd == "off":
return ""
elif hd in ("on", "cwd", "tmp"):
return "-XX:+HeapDumpOnOutOfMemoryError"
def get_perm_gen(self):
pg = self.settings.perm_gen
if str(pg).startswith("-XX"):
return pg
else:
return "-XX:MaxPermSize=%s" % pg
def get_append(self):
values = []
if self.settings.heap_dump == "tmp":
import tempfile
tmp = tempfile.gettempdir()
values.append("-XX:HeapDumpPath=%s" % tmp)
return values + split(self.settings.append)
def get_memory_settings(self):
values = [
self.get_heap_size(),
self.get_heap_dump(),
self.get_perm_gen(),
]
if any([x.startswith("-XX:MaxPermSize") for x in values]):
values.append("-XX:+IgnoreUnrecognizedVMOptions")
values += self.get_append()
return [x for x in values if x]
class ManualStrategy(Strategy):
"""
Simplest strategy which assumes all values have
been set and simply uses them or their defaults.
"""
class PercentStrategy(Strategy):
"""
Strategy based on a percent of available memory.
"""
PERCENT_DEFAULTS = (
("blitz", 15),
("pixeldata", 15),
("indexer", 10),
("repository", 10),
("other", 1),
)
def __init__(self, name, settings=None):
super(PercentStrategy, self).__init__(name, settings)
self.defaults = dict(self.PERCENT_DEFAULTS)
self.use_active = True
def get_heap_size(self):
"""
Uses the results of the default settings of
calculate_heap_size() as an argument to
get_heap_size(), in other words some percent
of the active memory.
"""
sz = self.calculate_heap_size()
return super(PercentStrategy, self).get_heap_size(sz)
def get_percent(self):
other = self.defaults.get("other", "1")
default = self.defaults.get(self.name, other)
percent = int(self.settings.lookup("percent", default))
return percent
def get_perm_gen(self):
available, active, total = self.system_memory_mb()
choice = self.use_active and active or total
if choice <= 4000:
if choice >= 2000:
self.settings.overwrite("perm_gen", "256m")
elif choice <= 8000:
self.settings.overwrite("perm_gen", "512m")
else:
self.settings.overwrite("perm_gen", "1g")
return super(PercentStrategy, self).get_perm_gen()
def calculate_heap_size(self, method=None):
"""
Re-calculates the appropriate heap size based on the
value of get_percent(). The "active" memory returned
by method() will be used by default, but can be modified
to use "total" via the "use_active" flag.
"""
if method is None:
method = self.system_memory_mb
available, active, total = method()
choice = self.use_active and active or total
percent = self.get_percent()
calculated = choice * int(percent) / 100
return calculated
def usage_table(self, min=10, max=20):
total_mb = [2**x for x in range(min, max)]
for total in total_mb:
method = lambda: (total, total, total)
yield total, self.calculate_heap_size(method)
STRATEGY_REGISTRY["manual"] = ManualStrategy
STRATEGY_REGISTRY["percent"] = PercentStrategy
def adjust_settings(config, template_xml,
blitz=None, indexer=None,
pixeldata=None, repository=None):
"""
Takes an omero.config.ConfigXml object and adjusts
the memory settings. Primary entry point to the
memory module.
"""
from xml.etree.ElementTree import Element
from collections import defaultdict
replacements = dict()
options = dict()
for template in template_xml.findall("server-template"):
for server in template.findall("server"):
for option in server.findall("option"):
o = option.text
if o.startswith("MEMORY:"):
options[o[7:]] = (server, option)
for props in server.findall("properties"):
for prop in props.findall("property"):
name = prop.attrib.get("name", "")
if name.startswith("REPLACEMENT:"):
replacements[name[12:]] = (server, prop)
rv = defaultdict(list)
m = config.as_map()
loop = (("blitz", blitz), ("indexer", indexer),
("pixeldata", pixeldata), ("repository", repository))
for name, StrategyType in loop:
if name not in options:
raise Exception(
"Cannot find %s option. Make sure templates.xml was "
"not copied from an older server" % name)
for name, StrategyType in loop:
specific = strip_dict(m, suffix=name)
defaults = strip_dict(m)
settings = Settings(specific, defaults)
rv[name].append(settings)
if StrategyType is None:
StrategyType = settings.get_strategy()
if not callable(StrategyType):
raise Exception("Bad strategy: %s" % StrategyType)
strategy = StrategyType(name, settings)
settings = strategy.get_memory_settings()
server, option = options[name]
idx = 0
for v in settings:
rv[name].append(v)
if idx == 0:
option.text = v
else:
elem = Element("option")
elem.text = v
server.insert(idx, elem)
idx += 1
# Now we check for any other properties and
# put them where the replacement should go.
for k, v in m.items():
r = []
suffix = ".%s" % name
size = len(suffix)
if k.endswith(suffix):
k = k[:-size]
r.append((k, v))
server, replacement = replacements[name]
idx = 0
for k, v in r:
if idx == 0:
replacement.attrib["name"] = k
replacement.attrib["value"] = v
else:
elem = Element("property", name=k, value=v)
server.append(elem)
return rv
def usage_charts(path,
min=0, max=20,
Strategy=PercentStrategy, name="blitz"):
# See http://matplotlib.org/examples/pylab_examples/anscombe.html
from pylab import array
from pylab import axis
from pylab import gca
from pylab import subplot
from pylab import plot
from pylab import setp
from pylab import savefig
from pylab import text
points = 200
x = array([2 ** (x / points) / 1000
for x in range(min*points, max*points)])
y_configs = (
(Settings({}), 'A'),
(Settings({"percent": "20"}), 'B'),
(Settings({}), 'C'),
(Settings({"max_system_memory": "10000"}), 'D'),
)
def f(cfg):
s = Strategy(name, settings=cfg[0])
y = []
for total in x:
method = lambda: (total, total, total)
y.append(s.calculate_heap_size(method))
return y
y1 = f(y_configs[0])
y2 = f(y_configs[1])
y3 = f(y_configs[2])
y4 = f(y_configs[3])
axis_values = [0, 20, 0, 6]
def ticks_f():
setp(gca(), xticks=(8, 16), yticks=(2, 4))
def text_f(which):
cfg = y_configs[which]
# s = cfg[0]
txt = "%s" % (cfg[1],)
text(2, 2, txt, fontsize=20)
subplot(221)
plot(x, y1)
axis(axis_values)
text_f(0)
ticks_f()
subplot(222)
plot(x, y2)
axis(axis_values)
text_f(1)
ticks_f()
subplot(223)
plot(x, y3)
axis(axis_values)
text_f(2)
ticks_f()
subplot(224)
plot(x, y4)
axis(axis_values)
text_f(3)
ticks_f()
savefig(path)
| if sz is None or self.settings.was_set("heap_size"):
sz = self.settings.heap_size
if str(sz).startswith("-X"):
return sz
else:
rv = "-Xmx%s" % sz
if rv[-1].lower() not in ("b", "k", "m", "g"):
rv = "%sm" % rv
return rv | identifier_body |
jvmcfg.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2014 Glencoe Software, Inc. All Rights Reserved.
# Use is subject to license terms supplied in LICENSE.txt
#
# 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.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""
Automatic configuration of memory settings for Java servers.
"""
from types import StringType
from shlex import split
import logging
LOGGER = logging.getLogger("omero.install.jvmcfg")
def strip_dict(map, prefix=("omero", "jvmcfg"), suffix=(), limit=1):
"""
For the given dictionary, return a copy of the
dictionary where all entries not matching the
prefix, suffix, and limit have been removed and
where all remaining keys have had the prefix and
suffix stripped. The limit describes the number
of elements that are allowed in the new key after
stripping prefix and suffix.
"""
if isinstance(prefix, StringType):
prefix = tuple(prefix.split("."))
if isinstance(suffix, StringType):
suffix = tuple(suffix.split("."))
rv = dict()
if not map:
return dict()
def __strip_dict(k, v, prefix, suffix, rv):
key = tuple(k.split("."))
ksz = len(key)
psz = len(prefix)
ssz = len(suffix)
if ksz <= (psz + ssz):
return # No way to strip if smaller
if key[0:psz] == prefix and key[ksz-ssz:] == suffix:
newkey = key[psz:ksz-ssz]
if len(newkey) == limit:
newkey = ".".join(newkey)
rv[newkey] = v
for k, v in map.items():
__strip_dict(k, v, prefix, suffix, rv)
return rv
class StrategyRegistry(dict):
def __init__(self, *args, **kwargs):
super(dict, self).__init__(*args, **kwargs)
STRATEGY_REGISTRY = StrategyRegistry()
class Settings(object):
"""
Container for the config options found in etc/grid/config.xml
"""
def __init__(self, server_values=None, global_values=None):
if server_values is None:
self.__server = dict()
else:
self.__server = server_values
if global_values is None:
self.__global = dict()
else:
self.__global = global_values
self.__static = {
"strategy": PercentStrategy,
"append": "",
"perm_gen": "128m",
"heap_dump": "off",
"heap_size": "512m",
"system_memory": None,
"max_system_memory": "48000",
"min_system_memory": "3414",
}
self.__manual = dict()
def __getattr__(self, key):
return self.lookup(key)
def lookup(self, key, default=None):
if key in self.__manual:
return self.__manual[key]
elif key in self.__server:
return self.__server[key]
elif key in self.__global:
return self.__global[key]
elif key in self.__static:
return self.__static[key]
else:
return default
def overwrite(self, key, value, always=False):
if self.was_set(key) and not always:
# Then we leave it as the user requested
return
else:
self.__manual[key] = value
def was_set(self, key):
return key in self.__server or key in self.__global
def get_strategy(self):
return STRATEGY_REGISTRY.get(self.strategy, self.strategy)
def __str__(self):
rv = dict()
rv.update(self.__server)
rv.update(self.__global)
if not rv:
rv = ""
return 'Settings(%s)' % rv
class Strategy(object):
"""
Strategy for calculating memory settings. Primary
class of the memory module.
"""
def __init__(self, name, settings=None):
"""
'name' argument should likely be one of:
('blitz', 'indexer', 'pixeldata', 'repository')
"""
if settings is None:
settings = Settings()
self.name = name
self.settings = settings
if type(self) == Strategy:
raise Exception("Must subclass!")
# Memory helpers
def system_memory_mb(self):
"""
Returns a tuple, in MB, of available, active, and total memory.
"total" memory is found by calling to first a Python library
(if installed) and otherwise a Java class. If
"system_memory" is set, it will short-circuit both methods.
"active" memory is set to "total" but limited by "min_system_memory"
and "max_system_memory".
"available" may not be accurate, and in some cases will be
set to total.
"""
available, total = None, None
if self.settings.system_memory is not None:
total = int(self.settings.system_memory)
available = total
else:
pymem = self._system_memory_mb_psutil()
if pymem is not None:
available, total = pymem
else:
available, total = self._system_memory_mb_java()
max_system_memory = int(self.settings.max_system_memory)
min_system_memory = int(self.settings.min_system_memory)
active = max(min(total, max_system_memory), min_system_memory)
return available, active, total
def _system_memory_mb_psutil(self):
try:
import psutil
pymem = psutil.virtual_memory()
return (pymem.free/1000000, pymem.total/1000000)
except ImportError:
LOGGER.debug("No psutil installed")
return None
def _system_memory_mb_java(self):
import omero.cli
import omero.java
# Copied from db.py. Needs better dir detection
cwd = omero.cli.CLI().dir
server_jar = cwd / "lib" / "server" / "server.jar"
cmd = ["ome.services.util.JvmSettingsCheck", "--psutil"]
p = omero.java.popen(["-cp", str(server_jar)] + cmd)
o, e = p.communicate()
if p.poll() != 0:
LOGGER.warn("Failed to invoke java:\nout:%s\nerr:%s",
o, e)
rv = dict()
for line in o.split("\n"):
line = line.strip()
if not line:
continue
parts = line.split(":")
if len(parts) == 1:
parts.append("")
rv[parts[0]] = parts[1]
try:
free = long(rv["Free"]) / 1000000
except:
LOGGER.warn("Failed to parse Free from %s", rv)
free = 2000
try:
total = long(rv["Total"]) / 1000000
except:
LOGGER.warn("Failed to parse Total from %s", rv)
total = 4000
return (free, total)
# API Getters
def get_heap_size(self, sz=None):
if sz is None or self.settings.was_set("heap_size"):
sz = self.settings.heap_size
if str(sz).startswith("-X"):
return sz
else:
rv = "-Xmx%s" % sz
if rv[-1].lower() not in ("b", "k", "m", "g"):
rv = "%sm" % rv
return rv
def get_heap_dump(self):
hd = self.settings.heap_dump
if hd == "off":
return ""
elif hd in ("on", "cwd", "tmp"):
return "-XX:+HeapDumpOnOutOfMemoryError"
def get_perm_gen(self):
pg = self.settings.perm_gen
if str(pg).startswith("-XX"):
return pg
else:
return "-XX:MaxPermSize=%s" % pg
def get_append(self):
values = []
if self.settings.heap_dump == "tmp":
import tempfile
tmp = tempfile.gettempdir()
values.append("-XX:HeapDumpPath=%s" % tmp)
return values + split(self.settings.append)
def get_memory_settings(self):
values = [
self.get_heap_size(),
self.get_heap_dump(),
self.get_perm_gen(),
]
if any([x.startswith("-XX:MaxPermSize") for x in values]):
values.append("-XX:+IgnoreUnrecognizedVMOptions")
values += self.get_append()
return [x for x in values if x]
class ManualStrategy(Strategy):
"""
Simplest strategy which assumes all values have
been set and simply uses them or their defaults.
"""
class PercentStrategy(Strategy):
"""
Strategy based on a percent of available memory.
"""
PERCENT_DEFAULTS = (
("blitz", 15),
("pixeldata", 15),
("indexer", 10),
("repository", 10),
("other", 1),
)
def __init__(self, name, settings=None):
super(PercentStrategy, self).__init__(name, settings)
self.defaults = dict(self.PERCENT_DEFAULTS)
self.use_active = True
def get_heap_size(self):
"""
Uses the results of the default settings of
calculate_heap_size() as an argument to
get_heap_size(), in other words some percent
of the active memory.
"""
sz = self.calculate_heap_size()
return super(PercentStrategy, self).get_heap_size(sz)
def get_percent(self):
other = self.defaults.get("other", "1")
default = self.defaults.get(self.name, other)
percent = int(self.settings.lookup("percent", default))
return percent
def get_perm_gen(self):
available, active, total = self.system_memory_mb()
choice = self.use_active and active or total
if choice <= 4000:
if choice >= 2000:
self.settings.overwrite("perm_gen", "256m")
elif choice <= 8000:
self.settings.overwrite("perm_gen", "512m")
else:
self.settings.overwrite("perm_gen", "1g")
return super(PercentStrategy, self).get_perm_gen()
def calculate_heap_size(self, method=None):
"""
Re-calculates the appropriate heap size based on the
value of get_percent(). The "active" memory returned
by method() will be used by default, but can be modified
to use "total" via the "use_active" flag.
"""
if method is None:
method = self.system_memory_mb
available, active, total = method()
choice = self.use_active and active or total
percent = self.get_percent()
calculated = choice * int(percent) / 100
return calculated
def usage_table(self, min=10, max=20):
total_mb = [2**x for x in range(min, max)]
for total in total_mb:
method = lambda: (total, total, total)
yield total, self.calculate_heap_size(method)
STRATEGY_REGISTRY["manual"] = ManualStrategy
STRATEGY_REGISTRY["percent"] = PercentStrategy
def adjust_settings(config, template_xml,
blitz=None, indexer=None,
pixeldata=None, repository=None):
"""
Takes an omero.config.ConfigXml object and adjusts
the memory settings. Primary entry point to the
memory module.
"""
from xml.etree.ElementTree import Element
from collections import defaultdict
replacements = dict()
options = dict()
for template in template_xml.findall("server-template"):
|
rv = defaultdict(list)
m = config.as_map()
loop = (("blitz", blitz), ("indexer", indexer),
("pixeldata", pixeldata), ("repository", repository))
for name, StrategyType in loop:
if name not in options:
raise Exception(
"Cannot find %s option. Make sure templates.xml was "
"not copied from an older server" % name)
for name, StrategyType in loop:
specific = strip_dict(m, suffix=name)
defaults = strip_dict(m)
settings = Settings(specific, defaults)
rv[name].append(settings)
if StrategyType is None:
StrategyType = settings.get_strategy()
if not callable(StrategyType):
raise Exception("Bad strategy: %s" % StrategyType)
strategy = StrategyType(name, settings)
settings = strategy.get_memory_settings()
server, option = options[name]
idx = 0
for v in settings:
rv[name].append(v)
if idx == 0:
option.text = v
else:
elem = Element("option")
elem.text = v
server.insert(idx, elem)
idx += 1
# Now we check for any other properties and
# put them where the replacement should go.
for k, v in m.items():
r = []
suffix = ".%s" % name
size = len(suffix)
if k.endswith(suffix):
k = k[:-size]
r.append((k, v))
server, replacement = replacements[name]
idx = 0
for k, v in r:
if idx == 0:
replacement.attrib["name"] = k
replacement.attrib["value"] = v
else:
elem = Element("property", name=k, value=v)
server.append(elem)
return rv
def usage_charts(path,
min=0, max=20,
Strategy=PercentStrategy, name="blitz"):
# See http://matplotlib.org/examples/pylab_examples/anscombe.html
from pylab import array
from pylab import axis
from pylab import gca
from pylab import subplot
from pylab import plot
from pylab import setp
from pylab import savefig
from pylab import text
points = 200
x = array([2 ** (x / points) / 1000
for x in range(min*points, max*points)])
y_configs = (
(Settings({}), 'A'),
(Settings({"percent": "20"}), 'B'),
(Settings({}), 'C'),
(Settings({"max_system_memory": "10000"}), 'D'),
)
def f(cfg):
s = Strategy(name, settings=cfg[0])
y = []
for total in x:
method = lambda: (total, total, total)
y.append(s.calculate_heap_size(method))
return y
y1 = f(y_configs[0])
y2 = f(y_configs[1])
y3 = f(y_configs[2])
y4 = f(y_configs[3])
axis_values = [0, 20, 0, 6]
def ticks_f():
setp(gca(), xticks=(8, 16), yticks=(2, 4))
def text_f(which):
cfg = y_configs[which]
# s = cfg[0]
txt = "%s" % (cfg[1],)
text(2, 2, txt, fontsize=20)
subplot(221)
plot(x, y1)
axis(axis_values)
text_f(0)
ticks_f()
subplot(222)
plot(x, y2)
axis(axis_values)
text_f(1)
ticks_f()
subplot(223)
plot(x, y3)
axis(axis_values)
text_f(2)
ticks_f()
subplot(224)
plot(x, y4)
axis(axis_values)
text_f(3)
ticks_f()
savefig(path)
| for server in template.findall("server"):
for option in server.findall("option"):
o = option.text
if o.startswith("MEMORY:"):
options[o[7:]] = (server, option)
for props in server.findall("properties"):
for prop in props.findall("property"):
name = prop.attrib.get("name", "")
if name.startswith("REPLACEMENT:"):
replacements[name[12:]] = (server, prop) | conditional_block |
stdio.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[cfg(stage0)]
use prelude::v1::*;
use io;
use libc;
use sys::fd::FileDesc;
pub struct Stdin(());
pub struct Stdout(());
pub struct Stderr(());
impl Stdin {
pub fn new() -> io::Result<Stdin> { Ok(Stdin(())) }
pub fn read(&self, data: &mut [u8]) -> io::Result<usize> {
let fd = FileDesc::new(libc::STDIN_FILENO);
let ret = fd.read(data);
fd.into_raw();
return ret;
}
}
impl Stdout {
pub fn new() -> io::Result<Stdout> |
pub fn write(&self, data: &[u8]) -> io::Result<usize> {
let fd = FileDesc::new(libc::STDOUT_FILENO);
let ret = fd.write(data);
fd.into_raw();
return ret;
}
}
impl Stderr {
pub fn new() -> io::Result<Stderr> { Ok(Stderr(())) }
pub fn write(&self, data: &[u8]) -> io::Result<usize> {
let fd = FileDesc::new(libc::STDERR_FILENO);
let ret = fd.write(data);
fd.into_raw();
return ret;
}
}
// FIXME: right now this raw stderr handle is used in a few places because
// std::io::stderr_raw isn't exposed, but once that's exposed this impl
// should go away
impl io::Write for Stderr {
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
Stderr::write(self, data)
}
fn flush(&mut self) -> io::Result<()> { Ok(()) }
}
| { Ok(Stdout(())) } | identifier_body |
stdio.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[cfg(stage0)]
use prelude::v1::*;
use io;
use libc;
use sys::fd::FileDesc;
pub struct Stdin(());
pub struct Stdout(());
pub struct | (());
impl Stdin {
pub fn new() -> io::Result<Stdin> { Ok(Stdin(())) }
pub fn read(&self, data: &mut [u8]) -> io::Result<usize> {
let fd = FileDesc::new(libc::STDIN_FILENO);
let ret = fd.read(data);
fd.into_raw();
return ret;
}
}
impl Stdout {
pub fn new() -> io::Result<Stdout> { Ok(Stdout(())) }
pub fn write(&self, data: &[u8]) -> io::Result<usize> {
let fd = FileDesc::new(libc::STDOUT_FILENO);
let ret = fd.write(data);
fd.into_raw();
return ret;
}
}
impl Stderr {
pub fn new() -> io::Result<Stderr> { Ok(Stderr(())) }
pub fn write(&self, data: &[u8]) -> io::Result<usize> {
let fd = FileDesc::new(libc::STDERR_FILENO);
let ret = fd.write(data);
fd.into_raw();
return ret;
}
}
// FIXME: right now this raw stderr handle is used in a few places because
// std::io::stderr_raw isn't exposed, but once that's exposed this impl
// should go away
impl io::Write for Stderr {
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
Stderr::write(self, data)
}
fn flush(&mut self) -> io::Result<()> { Ok(()) }
}
| Stderr | identifier_name |
stdio.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT. | // except according to those terms.
#[cfg(stage0)]
use prelude::v1::*;
use io;
use libc;
use sys::fd::FileDesc;
pub struct Stdin(());
pub struct Stdout(());
pub struct Stderr(());
impl Stdin {
pub fn new() -> io::Result<Stdin> { Ok(Stdin(())) }
pub fn read(&self, data: &mut [u8]) -> io::Result<usize> {
let fd = FileDesc::new(libc::STDIN_FILENO);
let ret = fd.read(data);
fd.into_raw();
return ret;
}
}
impl Stdout {
pub fn new() -> io::Result<Stdout> { Ok(Stdout(())) }
pub fn write(&self, data: &[u8]) -> io::Result<usize> {
let fd = FileDesc::new(libc::STDOUT_FILENO);
let ret = fd.write(data);
fd.into_raw();
return ret;
}
}
impl Stderr {
pub fn new() -> io::Result<Stderr> { Ok(Stderr(())) }
pub fn write(&self, data: &[u8]) -> io::Result<usize> {
let fd = FileDesc::new(libc::STDERR_FILENO);
let ret = fd.write(data);
fd.into_raw();
return ret;
}
}
// FIXME: right now this raw stderr handle is used in a few places because
// std::io::stderr_raw isn't exposed, but once that's exposed this impl
// should go away
impl io::Write for Stderr {
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
Stderr::write(self, data)
}
fn flush(&mut self) -> io::Result<()> { Ok(()) }
} | //
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed | random_line_split |
app.ts | /// <reference path="../../src/bobril.d.ts"/>
/// <reference path="../../src/bobril.onkey.d.ts"/>
module SandboxApp {
var imagesrc = "";
var PasteImageInput: IBobrilComponent = {
postInitDom(ctx: any, me: IBobrilNode, element: HTMLElement) {
ctx.element = element;
},
onKeyDown(ctx: any, k: IKeyDownUpEvent): boolean {
if (k.ctrl || k.meta) {
var p = document.getElementById("pastehack");
(<any>b.deref(p).ctx).element = ctx.element;
p.focus();
}
return false;
}
};
var PasteImageContEditable: IBobrilComponent = {
onKeyUp(ctx: any, k: IKeyDownUpEvent): boolean {
var el = <HTMLElement>ctx.selfelement;
var imgs = el.getElementsByTagName("img");
if (imgs.length > 0) {
imagesrc = imgs.item(0).getAttribute("src");
b.invalidate();
}
el.innerHTML = "\u00a0";
if (k.ctrl || k.meta) {
ctx.element.focus();
}
return false;
},
postInitDom(ctx: any, me: IBobrilNode, element: HTMLElement) {
ctx.selfelement = element;
element.addEventListener("paste", (ev: any) => {
var cbData: any;
if (ev.clipboardData) {
cbData = ev.clipboardData;
} else if ((<any>window).clipboardData) {
cbData = (<any>window).clipboardData;
}
if (cbData.items && cbData.items.length > 0) {
var blob = cbData.items[0].getAsFile();
var reader = new FileReader();
reader.onload = function (event: any) {
imagesrc = event.target.result;
b.invalidate();
}; // data url!
reader.readAsDataURL(blob);
return;
}
var fileList = cbData.files;
if (!fileList) {
console.log("fileList is null.");
return;
}
for (var i = 0; i < fileList.length; i++) {
var file = fileList[i];
var url = URL.createObjectURL(file); | ev.msConvertURL(file, "base64", url);
}
imagesrc = url;
b.invalidate();
} // for
});
}
};
b.init(() => {
b.invalidate();
return <IBobrilNode[]>[
{ tag: "h1", children: "Paste Image Sample" },
{ tag: "p", children: "Try to paste image into edit box using Ctrl+V (tested Chrome,Firefox,IE11)" },
{
tag: "input", attrs: { type: "text" }, component: PasteImageInput
},
{
tag: "div", attrs: { id: "pastehack", tabindex: "0", contentEditable: true }, style: { position: "fixed", opacity: 0 }, children: "\u00a0", component: PasteImageContEditable
},
{
tag: "div", children: imagesrc != "" && {
tag: "img", attrs: {
src: imagesrc
},
style: { width: "200px", height: "auto" }
}
}
];
});
} |
if (ev.convertURL) { // Use standard if available.
ev.convertURL(file, "base64", url);
} else { | random_line_split |
app.ts | /// <reference path="../../src/bobril.d.ts"/>
/// <reference path="../../src/bobril.onkey.d.ts"/>
module SandboxApp {
var imagesrc = "";
var PasteImageInput: IBobrilComponent = {
postInitDom(ctx: any, me: IBobrilNode, element: HTMLElement) {
ctx.element = element;
},
onKeyDown(ctx: any, k: IKeyDownUpEvent): boolean {
if (k.ctrl || k.meta) {
var p = document.getElementById("pastehack");
(<any>b.deref(p).ctx).element = ctx.element;
p.focus();
}
return false;
}
};
var PasteImageContEditable: IBobrilComponent = {
onKeyUp(ctx: any, k: IKeyDownUpEvent): boolean | ,
postInitDom(ctx: any, me: IBobrilNode, element: HTMLElement) {
ctx.selfelement = element;
element.addEventListener("paste", (ev: any) => {
var cbData: any;
if (ev.clipboardData) {
cbData = ev.clipboardData;
} else if ((<any>window).clipboardData) {
cbData = (<any>window).clipboardData;
}
if (cbData.items && cbData.items.length > 0) {
var blob = cbData.items[0].getAsFile();
var reader = new FileReader();
reader.onload = function (event: any) {
imagesrc = event.target.result;
b.invalidate();
}; // data url!
reader.readAsDataURL(blob);
return;
}
var fileList = cbData.files;
if (!fileList) {
console.log("fileList is null.");
return;
}
for (var i = 0; i < fileList.length; i++) {
var file = fileList[i];
var url = URL.createObjectURL(file);
if (ev.convertURL) { // Use standard if available.
ev.convertURL(file, "base64", url);
} else {
ev.msConvertURL(file, "base64", url);
}
imagesrc = url;
b.invalidate();
} // for
});
}
};
b.init(() => {
b.invalidate();
return <IBobrilNode[]>[
{ tag: "h1", children: "Paste Image Sample" },
{ tag: "p", children: "Try to paste image into edit box using Ctrl+V (tested Chrome,Firefox,IE11)" },
{
tag: "input", attrs: { type: "text" }, component: PasteImageInput
},
{
tag: "div", attrs: { id: "pastehack", tabindex: "0", contentEditable: true }, style: { position: "fixed", opacity: 0 }, children: "\u00a0", component: PasteImageContEditable
},
{
tag: "div", children: imagesrc != "" && {
tag: "img", attrs: {
src: imagesrc
},
style: { width: "200px", height: "auto" }
}
}
];
});
}
| {
var el = <HTMLElement>ctx.selfelement;
var imgs = el.getElementsByTagName("img");
if (imgs.length > 0) {
imagesrc = imgs.item(0).getAttribute("src");
b.invalidate();
}
el.innerHTML = "\u00a0";
if (k.ctrl || k.meta) {
ctx.element.focus();
}
return false;
} | identifier_body |
app.ts | /// <reference path="../../src/bobril.d.ts"/>
/// <reference path="../../src/bobril.onkey.d.ts"/>
module SandboxApp {
var imagesrc = "";
var PasteImageInput: IBobrilComponent = {
postInitDom(ctx: any, me: IBobrilNode, element: HTMLElement) {
ctx.element = element;
},
onKeyDown(ctx: any, k: IKeyDownUpEvent): boolean {
if (k.ctrl || k.meta) {
var p = document.getElementById("pastehack");
(<any>b.deref(p).ctx).element = ctx.element;
p.focus();
}
return false;
}
};
var PasteImageContEditable: IBobrilComponent = {
| (ctx: any, k: IKeyDownUpEvent): boolean {
var el = <HTMLElement>ctx.selfelement;
var imgs = el.getElementsByTagName("img");
if (imgs.length > 0) {
imagesrc = imgs.item(0).getAttribute("src");
b.invalidate();
}
el.innerHTML = "\u00a0";
if (k.ctrl || k.meta) {
ctx.element.focus();
}
return false;
},
postInitDom(ctx: any, me: IBobrilNode, element: HTMLElement) {
ctx.selfelement = element;
element.addEventListener("paste", (ev: any) => {
var cbData: any;
if (ev.clipboardData) {
cbData = ev.clipboardData;
} else if ((<any>window).clipboardData) {
cbData = (<any>window).clipboardData;
}
if (cbData.items && cbData.items.length > 0) {
var blob = cbData.items[0].getAsFile();
var reader = new FileReader();
reader.onload = function (event: any) {
imagesrc = event.target.result;
b.invalidate();
}; // data url!
reader.readAsDataURL(blob);
return;
}
var fileList = cbData.files;
if (!fileList) {
console.log("fileList is null.");
return;
}
for (var i = 0; i < fileList.length; i++) {
var file = fileList[i];
var url = URL.createObjectURL(file);
if (ev.convertURL) { // Use standard if available.
ev.convertURL(file, "base64", url);
} else {
ev.msConvertURL(file, "base64", url);
}
imagesrc = url;
b.invalidate();
} // for
});
}
};
b.init(() => {
b.invalidate();
return <IBobrilNode[]>[
{ tag: "h1", children: "Paste Image Sample" },
{ tag: "p", children: "Try to paste image into edit box using Ctrl+V (tested Chrome,Firefox,IE11)" },
{
tag: "input", attrs: { type: "text" }, component: PasteImageInput
},
{
tag: "div", attrs: { id: "pastehack", tabindex: "0", contentEditable: true }, style: { position: "fixed", opacity: 0 }, children: "\u00a0", component: PasteImageContEditable
},
{
tag: "div", children: imagesrc != "" && {
tag: "img", attrs: {
src: imagesrc
},
style: { width: "200px", height: "auto" }
}
}
];
});
}
| onKeyUp | identifier_name |
app.ts | /// <reference path="../../src/bobril.d.ts"/>
/// <reference path="../../src/bobril.onkey.d.ts"/>
module SandboxApp {
var imagesrc = "";
var PasteImageInput: IBobrilComponent = {
postInitDom(ctx: any, me: IBobrilNode, element: HTMLElement) {
ctx.element = element;
},
onKeyDown(ctx: any, k: IKeyDownUpEvent): boolean {
if (k.ctrl || k.meta) {
var p = document.getElementById("pastehack");
(<any>b.deref(p).ctx).element = ctx.element;
p.focus();
}
return false;
}
};
var PasteImageContEditable: IBobrilComponent = {
onKeyUp(ctx: any, k: IKeyDownUpEvent): boolean {
var el = <HTMLElement>ctx.selfelement;
var imgs = el.getElementsByTagName("img");
if (imgs.length > 0) {
imagesrc = imgs.item(0).getAttribute("src");
b.invalidate();
}
el.innerHTML = "\u00a0";
if (k.ctrl || k.meta) {
ctx.element.focus();
}
return false;
},
postInitDom(ctx: any, me: IBobrilNode, element: HTMLElement) {
ctx.selfelement = element;
element.addEventListener("paste", (ev: any) => {
var cbData: any;
if (ev.clipboardData) | else if ((<any>window).clipboardData) {
cbData = (<any>window).clipboardData;
}
if (cbData.items && cbData.items.length > 0) {
var blob = cbData.items[0].getAsFile();
var reader = new FileReader();
reader.onload = function (event: any) {
imagesrc = event.target.result;
b.invalidate();
}; // data url!
reader.readAsDataURL(blob);
return;
}
var fileList = cbData.files;
if (!fileList) {
console.log("fileList is null.");
return;
}
for (var i = 0; i < fileList.length; i++) {
var file = fileList[i];
var url = URL.createObjectURL(file);
if (ev.convertURL) { // Use standard if available.
ev.convertURL(file, "base64", url);
} else {
ev.msConvertURL(file, "base64", url);
}
imagesrc = url;
b.invalidate();
} // for
});
}
};
b.init(() => {
b.invalidate();
return <IBobrilNode[]>[
{ tag: "h1", children: "Paste Image Sample" },
{ tag: "p", children: "Try to paste image into edit box using Ctrl+V (tested Chrome,Firefox,IE11)" },
{
tag: "input", attrs: { type: "text" }, component: PasteImageInput
},
{
tag: "div", attrs: { id: "pastehack", tabindex: "0", contentEditable: true }, style: { position: "fixed", opacity: 0 }, children: "\u00a0", component: PasteImageContEditable
},
{
tag: "div", children: imagesrc != "" && {
tag: "img", attrs: {
src: imagesrc
},
style: { width: "200px", height: "auto" }
}
}
];
});
}
| {
cbData = ev.clipboardData;
} | conditional_block |
init.js | (function($){
$(function(){
var window_width = $(window).width();
// convert rgb to hex value string
function rgb2hex(rgb) {
if (/^#[0-9A-F]{6}$/i.test(rgb)) { return rgb; }
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
if (rgb === null) { return "N/A"; }
function hex(x) {
return ("0" + parseInt(x).toString(16)).slice(-2);
}
return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}
$('.dynamic-color .col').each(function () {
$(this).children().each(function () {
var color = $(this).css('background-color'),
classes = $(this).attr('class');
$(this).html(rgb2hex(color) + " " + classes);
if (classes.indexOf("darken") >= 0 || $(this).hasClass('black')) {
$(this).css('color', 'rgba(255,255,255,.9');
}
});
});
// Floating-Fixed table of contents
setTimeout(function() {
var tocWrapperHeight = 260; // Max height of ads.
var tocHeight = $('.toc-wrapper .table-of-contents').length ? $('.toc-wrapper .table-of-contents').height() : 0;
var socialHeight = 95; // Height of unloaded social media in footer.
var footerOffset = $('body > footer').first().length ? $('body > footer').first().offset().top : 0;
var bottomOffset = footerOffset - socialHeight - tocHeight - tocWrapperHeight;
var pushpinObj = {
bottom: bottomOffset
};
if ($('nav').length) {
pushpinObj.top = $('nav').height();
} else if ($('#index-banner').length) {
pushpinObj.top = $('#index-banner').height();
} else {
pushpinObj.top = 0;
}
if ($('.fixed-announcement').length) {
pushpinObj.top += 48;
}
$('.toc-wrapper').pushpin(pushpinObj);
}, 100);
// BuySellAds Detection
var $bsa = $(".buysellads"),
$timesToCheck = 3;
function checkForChanges() {
if (!$bsa.find('#carbonads').length) {
$timesToCheck -= 1;
if ($timesToCheck >= 0) {
setTimeout(checkForChanges, 500);
}
else {
var donateAd = $('<div id="carbonads"><span><a class="carbon-text" href="#!" onclick="document.getElementById(\'paypal-donate\').submit();"><img src="app/images/donate.png" /> Help support us by turning off adblock. If you still prefer to keep adblock on for this page but still want to support us, feel free to donate. Any little bit helps.</a></form></span></div>');
$bsa.append(donateAd);
}
}
}
checkForChanges();
// BuySellAds Demos close button.
$('.buysellads.buysellads-demo .close').on('click', function() {
$(this).parent().remove();
});
// Github Latest Commit
if ($('.github-commit').length) { // Checks if widget div exists (Index only)
$.ajax({
url: "https://api.github.com/repos/dogfalo/materialize/commits/master",
dataType: "json",
success: function (data) {
var sha = data.sha,
date = jQuery.timeago(data.commit.author.date);
if (window_width < 1120) {
sha = sha.substring(0,7);
}
$('.github-commit').find('.date').html(date);
$('.github-commit').find('.sha').html(sha).attr('href', data.html_url);
}
});
}
// Toggle Flow Text
var toggleFlowTextButton = $('#flow-toggle');
toggleFlowTextButton.click( function(){
$('#flow-text-demo').children('p').each(function(){
$(this).toggleClass('flow-text');
});
});
// Toggle Containers on page
var toggleContainersButton = $('#container-toggle-button');
toggleContainersButton.click(function(){
$('body .browser-window .container, .had-container').each(function(){
$(this).toggleClass('had-container');
$(this).toggleClass('container');
if ($(this).hasClass('container')) {
toggleContainersButton.text("Turn off Containers");
}
else {
toggleContainersButton.text("Turn on Containers");
}
});
});
// Detect touch screen and enable scrollbar if necessary
function is_touch_device() {
try {
document.createEvent("TouchEvent");
return true;
} catch (e) {
return false;
|
// Set checkbox on forms.html to indeterminate
var indeterminateCheckbox = document.getElementById('indeterminate-checkbox');
if (indeterminateCheckbox !== null)
indeterminateCheckbox.indeterminate = true;
// Pushpin Demo Init
if ($('.pushpin-demo-nav').length) {
$('.pushpin-demo-nav').each(function() {
var $this = $(this);
var $target = $('#' + $(this).attr('data-target'));
$this.pushpin({
top: $target.offset().top,
bottom: $target.offset().top + $target.outerHeight() - $this.height()
});
});
}
// CSS Transitions Demo Init
if ($('#scale-demo').length &&
$('#scale-demo-trigger').length) {
$('#scale-demo-trigger').click(function() {
$('#scale-demo').toggleClass('scale-out');
});
}
// Plugin initialization
$('.carousel.carousel-slider').carousel({fullWidth: true});
$('.carousel').carousel();
$('.slider').slider();
$('.parallax').parallax();
$('.modal').modal();
$('.scrollspy').scrollSpy();
$('.button-collapse').sideNav({'edge': 'left'});
$('.datepicker').pickadate({selectYears: 20});
$('.timepicker').pickatime();
$('select').not('.disabled').material_select();
$('input.autocomplete').autocomplete({
data: {"Apple": null, "Microsoft": null, "Google": 'http://placehold.it/250x250'},
});
}); // end of document ready
})(jQuery); // end of jQuery name space | }
}
if (is_touch_device()) {
$('#nav-mobile').css({ overflow: 'auto'});
}
| random_line_split |
init.js | (function($){
$(function(){
var window_width = $(window).width();
// convert rgb to hex value string
function rgb2hex(rgb) {
if (/^#[0-9A-F]{6}$/i.test(rgb)) { return rgb; }
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
if (rgb === null) { return "N/A"; }
function hex(x) {
return ("0" + parseInt(x).toString(16)).slice(-2);
}
return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}
$('.dynamic-color .col').each(function () {
$(this).children().each(function () {
var color = $(this).css('background-color'),
classes = $(this).attr('class');
$(this).html(rgb2hex(color) + " " + classes);
if (classes.indexOf("darken") >= 0 || $(this).hasClass('black')) {
$(this).css('color', 'rgba(255,255,255,.9');
}
});
});
// Floating-Fixed table of contents
setTimeout(function() {
var tocWrapperHeight = 260; // Max height of ads.
var tocHeight = $('.toc-wrapper .table-of-contents').length ? $('.toc-wrapper .table-of-contents').height() : 0;
var socialHeight = 95; // Height of unloaded social media in footer.
var footerOffset = $('body > footer').first().length ? $('body > footer').first().offset().top : 0;
var bottomOffset = footerOffset - socialHeight - tocHeight - tocWrapperHeight;
var pushpinObj = {
bottom: bottomOffset
};
if ($('nav').length) {
pushpinObj.top = $('nav').height();
} else if ($('#index-banner').length) {
pushpinObj.top = $('#index-banner').height();
} else {
pushpinObj.top = 0;
}
if ($('.fixed-announcement').length) {
pushpinObj.top += 48;
}
$('.toc-wrapper').pushpin(pushpinObj);
}, 100);
// BuySellAds Detection
var $bsa = $(".buysellads"),
$timesToCheck = 3;
function | () {
if (!$bsa.find('#carbonads').length) {
$timesToCheck -= 1;
if ($timesToCheck >= 0) {
setTimeout(checkForChanges, 500);
}
else {
var donateAd = $('<div id="carbonads"><span><a class="carbon-text" href="#!" onclick="document.getElementById(\'paypal-donate\').submit();"><img src="app/images/donate.png" /> Help support us by turning off adblock. If you still prefer to keep adblock on for this page but still want to support us, feel free to donate. Any little bit helps.</a></form></span></div>');
$bsa.append(donateAd);
}
}
}
checkForChanges();
// BuySellAds Demos close button.
$('.buysellads.buysellads-demo .close').on('click', function() {
$(this).parent().remove();
});
// Github Latest Commit
if ($('.github-commit').length) { // Checks if widget div exists (Index only)
$.ajax({
url: "https://api.github.com/repos/dogfalo/materialize/commits/master",
dataType: "json",
success: function (data) {
var sha = data.sha,
date = jQuery.timeago(data.commit.author.date);
if (window_width < 1120) {
sha = sha.substring(0,7);
}
$('.github-commit').find('.date').html(date);
$('.github-commit').find('.sha').html(sha).attr('href', data.html_url);
}
});
}
// Toggle Flow Text
var toggleFlowTextButton = $('#flow-toggle');
toggleFlowTextButton.click( function(){
$('#flow-text-demo').children('p').each(function(){
$(this).toggleClass('flow-text');
});
});
// Toggle Containers on page
var toggleContainersButton = $('#container-toggle-button');
toggleContainersButton.click(function(){
$('body .browser-window .container, .had-container').each(function(){
$(this).toggleClass('had-container');
$(this).toggleClass('container');
if ($(this).hasClass('container')) {
toggleContainersButton.text("Turn off Containers");
}
else {
toggleContainersButton.text("Turn on Containers");
}
});
});
// Detect touch screen and enable scrollbar if necessary
function is_touch_device() {
try {
document.createEvent("TouchEvent");
return true;
} catch (e) {
return false;
}
}
if (is_touch_device()) {
$('#nav-mobile').css({ overflow: 'auto'});
}
// Set checkbox on forms.html to indeterminate
var indeterminateCheckbox = document.getElementById('indeterminate-checkbox');
if (indeterminateCheckbox !== null)
indeterminateCheckbox.indeterminate = true;
// Pushpin Demo Init
if ($('.pushpin-demo-nav').length) {
$('.pushpin-demo-nav').each(function() {
var $this = $(this);
var $target = $('#' + $(this).attr('data-target'));
$this.pushpin({
top: $target.offset().top,
bottom: $target.offset().top + $target.outerHeight() - $this.height()
});
});
}
// CSS Transitions Demo Init
if ($('#scale-demo').length &&
$('#scale-demo-trigger').length) {
$('#scale-demo-trigger').click(function() {
$('#scale-demo').toggleClass('scale-out');
});
}
// Plugin initialization
$('.carousel.carousel-slider').carousel({fullWidth: true});
$('.carousel').carousel();
$('.slider').slider();
$('.parallax').parallax();
$('.modal').modal();
$('.scrollspy').scrollSpy();
$('.button-collapse').sideNav({'edge': 'left'});
$('.datepicker').pickadate({selectYears: 20});
$('.timepicker').pickatime();
$('select').not('.disabled').material_select();
$('input.autocomplete').autocomplete({
data: {"Apple": null, "Microsoft": null, "Google": 'http://placehold.it/250x250'},
});
}); // end of document ready
})(jQuery); // end of jQuery name space
| checkForChanges | identifier_name |
init.js | (function($){
$(function(){
var window_width = $(window).width();
// convert rgb to hex value string
function rgb2hex(rgb) {
if (/^#[0-9A-F]{6}$/i.test(rgb)) { return rgb; }
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
if (rgb === null) { return "N/A"; }
function hex(x) {
return ("0" + parseInt(x).toString(16)).slice(-2);
}
return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}
$('.dynamic-color .col').each(function () {
$(this).children().each(function () {
var color = $(this).css('background-color'),
classes = $(this).attr('class');
$(this).html(rgb2hex(color) + " " + classes);
if (classes.indexOf("darken") >= 0 || $(this).hasClass('black')) {
$(this).css('color', 'rgba(255,255,255,.9');
}
});
});
// Floating-Fixed table of contents
setTimeout(function() {
var tocWrapperHeight = 260; // Max height of ads.
var tocHeight = $('.toc-wrapper .table-of-contents').length ? $('.toc-wrapper .table-of-contents').height() : 0;
var socialHeight = 95; // Height of unloaded social media in footer.
var footerOffset = $('body > footer').first().length ? $('body > footer').first().offset().top : 0;
var bottomOffset = footerOffset - socialHeight - tocHeight - tocWrapperHeight;
var pushpinObj = {
bottom: bottomOffset
};
if ($('nav').length) {
pushpinObj.top = $('nav').height();
} else if ($('#index-banner').length) {
pushpinObj.top = $('#index-banner').height();
} else {
pushpinObj.top = 0;
}
if ($('.fixed-announcement').length) {
pushpinObj.top += 48;
}
$('.toc-wrapper').pushpin(pushpinObj);
}, 100);
// BuySellAds Detection
var $bsa = $(".buysellads"),
$timesToCheck = 3;
function checkForChanges() |
checkForChanges();
// BuySellAds Demos close button.
$('.buysellads.buysellads-demo .close').on('click', function() {
$(this).parent().remove();
});
// Github Latest Commit
if ($('.github-commit').length) { // Checks if widget div exists (Index only)
$.ajax({
url: "https://api.github.com/repos/dogfalo/materialize/commits/master",
dataType: "json",
success: function (data) {
var sha = data.sha,
date = jQuery.timeago(data.commit.author.date);
if (window_width < 1120) {
sha = sha.substring(0,7);
}
$('.github-commit').find('.date').html(date);
$('.github-commit').find('.sha').html(sha).attr('href', data.html_url);
}
});
}
// Toggle Flow Text
var toggleFlowTextButton = $('#flow-toggle');
toggleFlowTextButton.click( function(){
$('#flow-text-demo').children('p').each(function(){
$(this).toggleClass('flow-text');
});
});
// Toggle Containers on page
var toggleContainersButton = $('#container-toggle-button');
toggleContainersButton.click(function(){
$('body .browser-window .container, .had-container').each(function(){
$(this).toggleClass('had-container');
$(this).toggleClass('container');
if ($(this).hasClass('container')) {
toggleContainersButton.text("Turn off Containers");
}
else {
toggleContainersButton.text("Turn on Containers");
}
});
});
// Detect touch screen and enable scrollbar if necessary
function is_touch_device() {
try {
document.createEvent("TouchEvent");
return true;
} catch (e) {
return false;
}
}
if (is_touch_device()) {
$('#nav-mobile').css({ overflow: 'auto'});
}
// Set checkbox on forms.html to indeterminate
var indeterminateCheckbox = document.getElementById('indeterminate-checkbox');
if (indeterminateCheckbox !== null)
indeterminateCheckbox.indeterminate = true;
// Pushpin Demo Init
if ($('.pushpin-demo-nav').length) {
$('.pushpin-demo-nav').each(function() {
var $this = $(this);
var $target = $('#' + $(this).attr('data-target'));
$this.pushpin({
top: $target.offset().top,
bottom: $target.offset().top + $target.outerHeight() - $this.height()
});
});
}
// CSS Transitions Demo Init
if ($('#scale-demo').length &&
$('#scale-demo-trigger').length) {
$('#scale-demo-trigger').click(function() {
$('#scale-demo').toggleClass('scale-out');
});
}
// Plugin initialization
$('.carousel.carousel-slider').carousel({fullWidth: true});
$('.carousel').carousel();
$('.slider').slider();
$('.parallax').parallax();
$('.modal').modal();
$('.scrollspy').scrollSpy();
$('.button-collapse').sideNav({'edge': 'left'});
$('.datepicker').pickadate({selectYears: 20});
$('.timepicker').pickatime();
$('select').not('.disabled').material_select();
$('input.autocomplete').autocomplete({
data: {"Apple": null, "Microsoft": null, "Google": 'http://placehold.it/250x250'},
});
}); // end of document ready
})(jQuery); // end of jQuery name space
| {
if (!$bsa.find('#carbonads').length) {
$timesToCheck -= 1;
if ($timesToCheck >= 0) {
setTimeout(checkForChanges, 500);
}
else {
var donateAd = $('<div id="carbonads"><span><a class="carbon-text" href="#!" onclick="document.getElementById(\'paypal-donate\').submit();"><img src="app/images/donate.png" /> Help support us by turning off adblock. If you still prefer to keep adblock on for this page but still want to support us, feel free to donate. Any little bit helps.</a></form></span></div>');
$bsa.append(donateAd);
}
}
} | identifier_body |
init.js | (function($){
$(function(){
var window_width = $(window).width();
// convert rgb to hex value string
function rgb2hex(rgb) {
if (/^#[0-9A-F]{6}$/i.test(rgb)) { return rgb; }
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
if (rgb === null) { return "N/A"; }
function hex(x) {
return ("0" + parseInt(x).toString(16)).slice(-2);
}
return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}
$('.dynamic-color .col').each(function () {
$(this).children().each(function () {
var color = $(this).css('background-color'),
classes = $(this).attr('class');
$(this).html(rgb2hex(color) + " " + classes);
if (classes.indexOf("darken") >= 0 || $(this).hasClass('black')) {
$(this).css('color', 'rgba(255,255,255,.9');
}
});
});
// Floating-Fixed table of contents
setTimeout(function() {
var tocWrapperHeight = 260; // Max height of ads.
var tocHeight = $('.toc-wrapper .table-of-contents').length ? $('.toc-wrapper .table-of-contents').height() : 0;
var socialHeight = 95; // Height of unloaded social media in footer.
var footerOffset = $('body > footer').first().length ? $('body > footer').first().offset().top : 0;
var bottomOffset = footerOffset - socialHeight - tocHeight - tocWrapperHeight;
var pushpinObj = {
bottom: bottomOffset
};
if ($('nav').length) {
pushpinObj.top = $('nav').height();
} else if ($('#index-banner').length) {
pushpinObj.top = $('#index-banner').height();
} else {
pushpinObj.top = 0;
}
if ($('.fixed-announcement').length) {
pushpinObj.top += 48;
}
$('.toc-wrapper').pushpin(pushpinObj);
}, 100);
// BuySellAds Detection
var $bsa = $(".buysellads"),
$timesToCheck = 3;
function checkForChanges() {
if (!$bsa.find('#carbonads').length) {
$timesToCheck -= 1;
if ($timesToCheck >= 0) {
setTimeout(checkForChanges, 500);
}
else {
var donateAd = $('<div id="carbonads"><span><a class="carbon-text" href="#!" onclick="document.getElementById(\'paypal-donate\').submit();"><img src="app/images/donate.png" /> Help support us by turning off adblock. If you still prefer to keep adblock on for this page but still want to support us, feel free to donate. Any little bit helps.</a></form></span></div>');
$bsa.append(donateAd);
}
}
}
checkForChanges();
// BuySellAds Demos close button.
$('.buysellads.buysellads-demo .close').on('click', function() {
$(this).parent().remove();
});
// Github Latest Commit
if ($('.github-commit').length) { // Checks if widget div exists (Index only)
$.ajax({
url: "https://api.github.com/repos/dogfalo/materialize/commits/master",
dataType: "json",
success: function (data) {
var sha = data.sha,
date = jQuery.timeago(data.commit.author.date);
if (window_width < 1120) {
sha = sha.substring(0,7);
}
$('.github-commit').find('.date').html(date);
$('.github-commit').find('.sha').html(sha).attr('href', data.html_url);
}
});
}
// Toggle Flow Text
var toggleFlowTextButton = $('#flow-toggle');
toggleFlowTextButton.click( function(){
$('#flow-text-demo').children('p').each(function(){
$(this).toggleClass('flow-text');
});
});
// Toggle Containers on page
var toggleContainersButton = $('#container-toggle-button');
toggleContainersButton.click(function(){
$('body .browser-window .container, .had-container').each(function(){
$(this).toggleClass('had-container');
$(this).toggleClass('container');
if ($(this).hasClass('container')) {
toggleContainersButton.text("Turn off Containers");
}
else {
toggleContainersButton.text("Turn on Containers");
}
});
});
// Detect touch screen and enable scrollbar if necessary
function is_touch_device() {
try {
document.createEvent("TouchEvent");
return true;
} catch (e) {
return false;
}
}
if (is_touch_device()) |
// Set checkbox on forms.html to indeterminate
var indeterminateCheckbox = document.getElementById('indeterminate-checkbox');
if (indeterminateCheckbox !== null)
indeterminateCheckbox.indeterminate = true;
// Pushpin Demo Init
if ($('.pushpin-demo-nav').length) {
$('.pushpin-demo-nav').each(function() {
var $this = $(this);
var $target = $('#' + $(this).attr('data-target'));
$this.pushpin({
top: $target.offset().top,
bottom: $target.offset().top + $target.outerHeight() - $this.height()
});
});
}
// CSS Transitions Demo Init
if ($('#scale-demo').length &&
$('#scale-demo-trigger').length) {
$('#scale-demo-trigger').click(function() {
$('#scale-demo').toggleClass('scale-out');
});
}
// Plugin initialization
$('.carousel.carousel-slider').carousel({fullWidth: true});
$('.carousel').carousel();
$('.slider').slider();
$('.parallax').parallax();
$('.modal').modal();
$('.scrollspy').scrollSpy();
$('.button-collapse').sideNav({'edge': 'left'});
$('.datepicker').pickadate({selectYears: 20});
$('.timepicker').pickatime();
$('select').not('.disabled').material_select();
$('input.autocomplete').autocomplete({
data: {"Apple": null, "Microsoft": null, "Google": 'http://placehold.it/250x250'},
});
}); // end of document ready
})(jQuery); // end of jQuery name space
| {
$('#nav-mobile').css({ overflow: 'auto'});
} | conditional_block |
cttz32.rs | #![feature(core, core_intrinsics)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::cttz32;
// pub fn cttz32(x: u32) -> u32;
macro_rules! cttz32_test {
($value:expr, $BITS:expr) => ({
let x: u32 = $value;
let result: u32 = unsafe { cttz32(x) };
assert_eq!(result, $BITS);
})
}
#[test]
fn cttz32_test1() |
}
| {
cttz32_test!(0x00000001, 0);
cttz32_test!(0x00000002, 1);
cttz32_test!(0x00000004, 2);
cttz32_test!(0x00000008, 3);
cttz32_test!(0x00000010, 4);
cttz32_test!(0x00000020, 5);
cttz32_test!(0x00000040, 6);
cttz32_test!(0x00000080, 7);
cttz32_test!(0x00000100, 8);
cttz32_test!(0x00000200, 9);
cttz32_test!(0x00000400, 10);
cttz32_test!(0x00000800, 11);
cttz32_test!(0x00001000, 12);
cttz32_test!(0x00002000, 13);
cttz32_test!(0x00004000, 14);
cttz32_test!(0x00008000, 15);
cttz32_test!(0x00010000, 16);
cttz32_test!(0x00020000, 17);
cttz32_test!(0x00040000, 18);
cttz32_test!(0x00080000, 19);
cttz32_test!(0x00100000, 20);
cttz32_test!(0x00200000, 21);
cttz32_test!(0x00400000, 22);
cttz32_test!(0x00800000, 23);
cttz32_test!(0x01000000, 24);
cttz32_test!(0x02000000, 25);
cttz32_test!(0x04000000, 26);
cttz32_test!(0x08000000, 27);
cttz32_test!(0x10000000, 28);
cttz32_test!(0x20000000, 29);
cttz32_test!(0x40000000, 30);
cttz32_test!(0x80000000, 31);
} | identifier_body |
cttz32.rs | #![feature(core, core_intrinsics)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::cttz32;
// pub fn cttz32(x: u32) -> u32;
macro_rules! cttz32_test {
($value:expr, $BITS:expr) => ({
let x: u32 = $value;
let result: u32 = unsafe { cttz32(x) };
assert_eq!(result, $BITS);
})
}
#[test]
fn | () {
cttz32_test!(0x00000001, 0);
cttz32_test!(0x00000002, 1);
cttz32_test!(0x00000004, 2);
cttz32_test!(0x00000008, 3);
cttz32_test!(0x00000010, 4);
cttz32_test!(0x00000020, 5);
cttz32_test!(0x00000040, 6);
cttz32_test!(0x00000080, 7);
cttz32_test!(0x00000100, 8);
cttz32_test!(0x00000200, 9);
cttz32_test!(0x00000400, 10);
cttz32_test!(0x00000800, 11);
cttz32_test!(0x00001000, 12);
cttz32_test!(0x00002000, 13);
cttz32_test!(0x00004000, 14);
cttz32_test!(0x00008000, 15);
cttz32_test!(0x00010000, 16);
cttz32_test!(0x00020000, 17);
cttz32_test!(0x00040000, 18);
cttz32_test!(0x00080000, 19);
cttz32_test!(0x00100000, 20);
cttz32_test!(0x00200000, 21);
cttz32_test!(0x00400000, 22);
cttz32_test!(0x00800000, 23);
cttz32_test!(0x01000000, 24);
cttz32_test!(0x02000000, 25);
cttz32_test!(0x04000000, 26);
cttz32_test!(0x08000000, 27);
cttz32_test!(0x10000000, 28);
cttz32_test!(0x20000000, 29);
cttz32_test!(0x40000000, 30);
cttz32_test!(0x80000000, 31);
}
}
| cttz32_test1 | identifier_name |
cttz32.rs | #![feature(core, core_intrinsics)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::cttz32;
// pub fn cttz32(x: u32) -> u32;
macro_rules! cttz32_test {
($value:expr, $BITS:expr) => ({
let x: u32 = $value;
let result: u32 = unsafe { cttz32(x) };
assert_eq!(result, $BITS);
})
}
#[test]
fn cttz32_test1() {
cttz32_test!(0x00000001, 0);
cttz32_test!(0x00000002, 1);
cttz32_test!(0x00000004, 2);
cttz32_test!(0x00000008, 3); | cttz32_test!(0x00000080, 7);
cttz32_test!(0x00000100, 8);
cttz32_test!(0x00000200, 9);
cttz32_test!(0x00000400, 10);
cttz32_test!(0x00000800, 11);
cttz32_test!(0x00001000, 12);
cttz32_test!(0x00002000, 13);
cttz32_test!(0x00004000, 14);
cttz32_test!(0x00008000, 15);
cttz32_test!(0x00010000, 16);
cttz32_test!(0x00020000, 17);
cttz32_test!(0x00040000, 18);
cttz32_test!(0x00080000, 19);
cttz32_test!(0x00100000, 20);
cttz32_test!(0x00200000, 21);
cttz32_test!(0x00400000, 22);
cttz32_test!(0x00800000, 23);
cttz32_test!(0x01000000, 24);
cttz32_test!(0x02000000, 25);
cttz32_test!(0x04000000, 26);
cttz32_test!(0x08000000, 27);
cttz32_test!(0x10000000, 28);
cttz32_test!(0x20000000, 29);
cttz32_test!(0x40000000, 30);
cttz32_test!(0x80000000, 31);
}
} | cttz32_test!(0x00000010, 4);
cttz32_test!(0x00000020, 5);
cttz32_test!(0x00000040, 6); | random_line_split |
afos_dump.py | """AFOS Database Workflow."""
# 3rd Party
from twisted.internet import reactor
from txyam.client import YamClient
from pyiem.util import LOG
from pyiem.nws import product
# Local
from pywwa import common
from pywwa.ldm import bridge
from pywwa.database import get_database
DBPOOL = get_database("afos", cp_max=5)
MEMCACHE_EXCLUDE = [
"RR1",
"RR2",
"RR3",
"RR4",
"RR5",
"RR6",
"RR7",
"RR8",
"RR9",
"ROB",
"HML",
]
MEMCACHE_CLIENT = YamClient(reactor, ["tcp:iem-memcached3:11211"])
MEMCACHE_CLIENT.connect()
def process_data(data):
"""Process the product"""
defer = DBPOOL.runInteraction(real_parser, data)
defer.addCallback(write_memcache)
defer.addErrback(common.email_error, data)
defer.addErrback(LOG.error)
def write_memcache(nws):
"""write our TextProduct to memcached"""
if nws is None:
return
# 10 minutes should be enough time
LOG.debug("writing %s to memcache", nws.get_product_id())
df = MEMCACHE_CLIENT.set(
nws.get_product_id().encode("utf-8"),
nws.unixtext.replace("\001\n", "").encode("utf-8"),
expireTime=600,
)
df.addErrback(LOG.error)
def real_parser(txn, buf):
"""Actually do something with the buffer, please"""
if buf.strip() == "":
return None
utcnow = common.utcnow()
nws = product.TextProduct(buf, utcnow=utcnow, parse_segments=False)
# When we are in realtime processing, do not consider old data, typically
# when a WFO fails to update the date in their MND
if not common.replace_enabled() and (
(utcnow - nws.valid).days > 180 or (utcnow - nws.valid).days < -180
):
raise Exception(f"Very Latent Product! {nws.valid}")
if nws.warnings:
common.email_error("\n".join(nws.warnings), buf)
if nws.afos is None:
if nws.source[0] not in ["K", "P"]:
return None
raise Exception("TextProduct.afos is null")
if common.replace_enabled():
args = [nws.afos.strip(), nws.source, nws.valid]
bbb = ""
if nws.bbb:
|
txn.execute(
"DELETE from products where pil = %s and source = %s and "
f"entered = %s {bbb}",
args,
)
LOG.info("Removed %s rows for %s", txn.rowcount, nws.get_product_id())
txn.execute(
"INSERT into products (pil, data, entered, "
"source, wmo, bbb) VALUES(%s, %s, %s, %s, %s, %s)",
(nws.afos.strip(), nws.text, nws.valid, nws.source, nws.wmo, nws.bbb),
)
if nws.afos[:3] in MEMCACHE_EXCLUDE:
return None
return nws
def main():
"""Fire up our workflow."""
common.main(with_jabber=False)
bridge(process_data)
reactor.run() # @UndefinedVariable
# See how we are called.
if __name__ == "__main__":
main()
| bbb = " and bbb = %s "
args.append(nws.bbb) | conditional_block |
afos_dump.py | """AFOS Database Workflow."""
# 3rd Party
from twisted.internet import reactor
from txyam.client import YamClient
from pyiem.util import LOG
from pyiem.nws import product
# Local
from pywwa import common
from pywwa.ldm import bridge
from pywwa.database import get_database
DBPOOL = get_database("afos", cp_max=5)
MEMCACHE_EXCLUDE = [
"RR1",
"RR2",
"RR3",
"RR4",
"RR5",
"RR6",
"RR7",
"RR8",
"RR9",
"ROB",
"HML",
]
MEMCACHE_CLIENT = YamClient(reactor, ["tcp:iem-memcached3:11211"])
MEMCACHE_CLIENT.connect()
def process_data(data):
"""Process the product"""
defer = DBPOOL.runInteraction(real_parser, data)
defer.addCallback(write_memcache)
defer.addErrback(common.email_error, data)
defer.addErrback(LOG.error)
def write_memcache(nws):
"""write our TextProduct to memcached"""
if nws is None:
return
# 10 minutes should be enough time
LOG.debug("writing %s to memcache", nws.get_product_id())
df = MEMCACHE_CLIENT.set(
nws.get_product_id().encode("utf-8"),
nws.unixtext.replace("\001\n", "").encode("utf-8"),
expireTime=600,
)
df.addErrback(LOG.error)
def real_parser(txn, buf):
"""Actually do something with the buffer, please"""
if buf.strip() == "":
return None
utcnow = common.utcnow()
nws = product.TextProduct(buf, utcnow=utcnow, parse_segments=False)
# When we are in realtime processing, do not consider old data, typically
# when a WFO fails to update the date in their MND
if not common.replace_enabled() and (
(utcnow - nws.valid).days > 180 or (utcnow - nws.valid).days < -180
):
raise Exception(f"Very Latent Product! {nws.valid}")
if nws.warnings:
common.email_error("\n".join(nws.warnings), buf)
if nws.afos is None:
if nws.source[0] not in ["K", "P"]:
return None
raise Exception("TextProduct.afos is null")
if common.replace_enabled():
args = [nws.afos.strip(), nws.source, nws.valid]
bbb = ""
if nws.bbb:
bbb = " and bbb = %s "
args.append(nws.bbb)
txn.execute(
"DELETE from products where pil = %s and source = %s and "
f"entered = %s {bbb}",
args,
)
LOG.info("Removed %s rows for %s", txn.rowcount, nws.get_product_id())
txn.execute(
"INSERT into products (pil, data, entered, "
"source, wmo, bbb) VALUES(%s, %s, %s, %s, %s, %s)",
(nws.afos.strip(), nws.text, nws.valid, nws.source, nws.wmo, nws.bbb),
)
if nws.afos[:3] in MEMCACHE_EXCLUDE:
return None
return nws
def | ():
"""Fire up our workflow."""
common.main(with_jabber=False)
bridge(process_data)
reactor.run() # @UndefinedVariable
# See how we are called.
if __name__ == "__main__":
main()
| main | identifier_name |
afos_dump.py | """AFOS Database Workflow."""
# 3rd Party
from twisted.internet import reactor
from txyam.client import YamClient
from pyiem.util import LOG
from pyiem.nws import product
# Local
from pywwa import common
from pywwa.ldm import bridge
from pywwa.database import get_database
DBPOOL = get_database("afos", cp_max=5)
MEMCACHE_EXCLUDE = [
"RR1",
"RR2",
"RR3",
"RR4",
"RR5",
"RR6",
"RR7",
"RR8",
"RR9",
"ROB",
"HML",
]
MEMCACHE_CLIENT = YamClient(reactor, ["tcp:iem-memcached3:11211"])
MEMCACHE_CLIENT.connect()
def process_data(data):
"""Process the product"""
defer = DBPOOL.runInteraction(real_parser, data)
defer.addCallback(write_memcache)
defer.addErrback(common.email_error, data)
defer.addErrback(LOG.error)
def write_memcache(nws):
"""write our TextProduct to memcached"""
if nws is None:
return
# 10 minutes should be enough time
LOG.debug("writing %s to memcache", nws.get_product_id())
df = MEMCACHE_CLIENT.set(
nws.get_product_id().encode("utf-8"),
nws.unixtext.replace("\001\n", "").encode("utf-8"),
expireTime=600,
)
df.addErrback(LOG.error)
def real_parser(txn, buf):
"""Actually do something with the buffer, please"""
if buf.strip() == "":
return None
utcnow = common.utcnow()
nws = product.TextProduct(buf, utcnow=utcnow, parse_segments=False)
# When we are in realtime processing, do not consider old data, typically
# when a WFO fails to update the date in their MND
if not common.replace_enabled() and (
(utcnow - nws.valid).days > 180 or (utcnow - nws.valid).days < -180
):
raise Exception(f"Very Latent Product! {nws.valid}")
if nws.warnings:
common.email_error("\n".join(nws.warnings), buf)
if nws.afos is None:
if nws.source[0] not in ["K", "P"]:
return None
raise Exception("TextProduct.afos is null")
if common.replace_enabled():
args = [nws.afos.strip(), nws.source, nws.valid]
bbb = ""
if nws.bbb:
bbb = " and bbb = %s "
args.append(nws.bbb)
txn.execute(
"DELETE from products where pil = %s and source = %s and "
f"entered = %s {bbb}",
args,
)
LOG.info("Removed %s rows for %s", txn.rowcount, nws.get_product_id())
txn.execute(
"INSERT into products (pil, data, entered, " | )
if nws.afos[:3] in MEMCACHE_EXCLUDE:
return None
return nws
def main():
"""Fire up our workflow."""
common.main(with_jabber=False)
bridge(process_data)
reactor.run() # @UndefinedVariable
# See how we are called.
if __name__ == "__main__":
main() | "source, wmo, bbb) VALUES(%s, %s, %s, %s, %s, %s)",
(nws.afos.strip(), nws.text, nws.valid, nws.source, nws.wmo, nws.bbb), | random_line_split |
afos_dump.py | """AFOS Database Workflow."""
# 3rd Party
from twisted.internet import reactor
from txyam.client import YamClient
from pyiem.util import LOG
from pyiem.nws import product
# Local
from pywwa import common
from pywwa.ldm import bridge
from pywwa.database import get_database
DBPOOL = get_database("afos", cp_max=5)
MEMCACHE_EXCLUDE = [
"RR1",
"RR2",
"RR3",
"RR4",
"RR5",
"RR6",
"RR7",
"RR8",
"RR9",
"ROB",
"HML",
]
MEMCACHE_CLIENT = YamClient(reactor, ["tcp:iem-memcached3:11211"])
MEMCACHE_CLIENT.connect()
def process_data(data):
"""Process the product"""
defer = DBPOOL.runInteraction(real_parser, data)
defer.addCallback(write_memcache)
defer.addErrback(common.email_error, data)
defer.addErrback(LOG.error)
def write_memcache(nws):
"""write our TextProduct to memcached"""
if nws is None:
return
# 10 minutes should be enough time
LOG.debug("writing %s to memcache", nws.get_product_id())
df = MEMCACHE_CLIENT.set(
nws.get_product_id().encode("utf-8"),
nws.unixtext.replace("\001\n", "").encode("utf-8"),
expireTime=600,
)
df.addErrback(LOG.error)
def real_parser(txn, buf):
"""Actually do something with the buffer, please"""
if buf.strip() == "":
return None
utcnow = common.utcnow()
nws = product.TextProduct(buf, utcnow=utcnow, parse_segments=False)
# When we are in realtime processing, do not consider old data, typically
# when a WFO fails to update the date in their MND
if not common.replace_enabled() and (
(utcnow - nws.valid).days > 180 or (utcnow - nws.valid).days < -180
):
raise Exception(f"Very Latent Product! {nws.valid}")
if nws.warnings:
common.email_error("\n".join(nws.warnings), buf)
if nws.afos is None:
if nws.source[0] not in ["K", "P"]:
return None
raise Exception("TextProduct.afos is null")
if common.replace_enabled():
args = [nws.afos.strip(), nws.source, nws.valid]
bbb = ""
if nws.bbb:
bbb = " and bbb = %s "
args.append(nws.bbb)
txn.execute(
"DELETE from products where pil = %s and source = %s and "
f"entered = %s {bbb}",
args,
)
LOG.info("Removed %s rows for %s", txn.rowcount, nws.get_product_id())
txn.execute(
"INSERT into products (pil, data, entered, "
"source, wmo, bbb) VALUES(%s, %s, %s, %s, %s, %s)",
(nws.afos.strip(), nws.text, nws.valid, nws.source, nws.wmo, nws.bbb),
)
if nws.afos[:3] in MEMCACHE_EXCLUDE:
return None
return nws
def main():
|
# See how we are called.
if __name__ == "__main__":
main()
| """Fire up our workflow."""
common.main(with_jabber=False)
bridge(process_data)
reactor.run() # @UndefinedVariable | identifier_body |
people-v3-qunit-test.js | import { test, module } from 'qunit';
import { setupTest } from 'ember-qunit';
import { setupPact, given, interaction } from 'ember-cli-pact';
import { run } from '@ember/runloop';
module('Pact | People', function(hooks) {
setupTest(hooks); |
test('listing people', async function(assert) {
given('a department exists', { id: '1', name: 'People' });
given('a person exists', { id: '1', name: 'Alice', departmentId: '1' });
given('a person exists', { id: '2', name: 'Bob', departmentId: '1' });
let people = await interaction(() => this.store().findAll('person'));
assert.deepEqual([...people.mapBy('id')], ['1', '2']);
assert.deepEqual([...people.mapBy('name')], ['Alice', 'Bob']);
assert.deepEqual([...people.mapBy('department.name')], ['People', 'People']);
});
test('querying people', async function(assert) {
given('a person exists', { id: '1', name: 'Alice' });
given('a person exists', { id: '2', name: 'Bob' });
let people = await interaction(() => this.store().query('person', { name: 'Bob' }));
assert.equal(people.get('length'), 1);
assert.equal(people.get('firstObject.id'), '2');
assert.equal(people.get('firstObject.name'), 'Bob');
});
test('fetching a person by ID', async function(assert) {
given('a person exists', { id: '1', name: 'Alice' });
let person = await interaction(() => this.store().findRecord('person', '1'));
assert.equal(person.get('id'), '1');
assert.equal(person.get('name'), 'Alice');
});
test('updating a person', async function(assert) {
given('a person exists', { id: '1', name: 'Alice' });
let person = await run(() => this.store().findRecord('person', '1'));
await interaction(() => {
person.set('name', 'Alicia');
return person.save();
});
assert.equal(person.get('name'), 'Alicia');
});
}); | setupPact(hooks); | random_line_split |
classie.js | /*!
* classie - class helper functions
* from bonzo https://github.com/ded/bonzo
*
* classie.has( elem, 'my-class' ) -> true/false
* classie.add( elem, 'my-new-class' )
* classie.remove( elem, 'my-unwanted-class' )
*/
/*jshint browser: true, strict: true, undef: true */
( function( window ) {
'use strict';
// class helper functions from bonzo https://github.com/ded/bonzo
function classReg( className ) {
return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
}
// classList support for class management
// altho to be fair, the api sucks because it won't accept multiple classes at once
var hasClass, addClass, removeClass;
if ( 'classList' in document.documentElement ) |
else {
hasClass = function( elem, c ) {
return classReg( c ).test( elem.className );
};
addClass = function( elem, c ) {
if ( !hasClass( elem, c ) ) {
elem.className = elem.className + ' ' + c;
}
};
removeClass = function( elem, c ) {
elem.className = elem.className.replace( classReg( c ), ' ' );
};
}
window.classie = {
// full names
hasClass: hasClass,
addClass: addClass,
removeClass: removeClass,
// short names
has: hasClass,
add: addClass,
remove: removeClass
};
})( window );
| {
hasClass = function( elem, c ) {
return elem.classList.contains( c );
};
addClass = function( elem, c ) {
elem.classList.add( c );
};
removeClass = function( elem, c ) {
elem.classList.remove( c );
};
} | conditional_block |
classie.js | /*!
* classie - class helper functions
* from bonzo https://github.com/ded/bonzo
*
* classie.has( elem, 'my-class' ) -> true/false
* classie.add( elem, 'my-new-class' )
* classie.remove( elem, 'my-unwanted-class' )
*/
/*jshint browser: true, strict: true, undef: true */
( function( window ) {
'use strict';
// class helper functions from bonzo https://github.com/ded/bonzo
function classReg( className ) |
// classList support for class management
// altho to be fair, the api sucks because it won't accept multiple classes at once
var hasClass, addClass, removeClass;
if ( 'classList' in document.documentElement ) {
hasClass = function( elem, c ) {
return elem.classList.contains( c );
};
addClass = function( elem, c ) {
elem.classList.add( c );
};
removeClass = function( elem, c ) {
elem.classList.remove( c );
};
}
else {
hasClass = function( elem, c ) {
return classReg( c ).test( elem.className );
};
addClass = function( elem, c ) {
if ( !hasClass( elem, c ) ) {
elem.className = elem.className + ' ' + c;
}
};
removeClass = function( elem, c ) {
elem.className = elem.className.replace( classReg( c ), ' ' );
};
}
window.classie = {
// full names
hasClass: hasClass,
addClass: addClass,
removeClass: removeClass,
// short names
has: hasClass,
add: addClass,
remove: removeClass
};
})( window );
| {
return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
} | identifier_body |
classie.js | /*!
* classie - class helper functions
* from bonzo https://github.com/ded/bonzo
*
* classie.has( elem, 'my-class' ) -> true/false
* classie.add( elem, 'my-new-class' )
* classie.remove( elem, 'my-unwanted-class' )
*/
/*jshint browser: true, strict: true, undef: true */
( function( window ) {
'use strict';
// class helper functions from bonzo https://github.com/ded/bonzo
function classReg( className ) {
return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
}
// classList support for class management
// altho to be fair, the api sucks because it won't accept multiple classes at once
var hasClass, addClass, removeClass;
if ( 'classList' in document.documentElement ) {
hasClass = function( elem, c ) {
return elem.classList.contains( c );
};
addClass = function( elem, c ) {
elem.classList.add( c );
};
removeClass = function( elem, c ) {
elem.classList.remove( c );
};
}
else {
hasClass = function( elem, c ) {
return classReg( c ).test( elem.className );
};
addClass = function( elem, c ) {
if ( !hasClass( elem, c ) ) {
elem.className = elem.className + ' ' + c;
}
};
removeClass = function( elem, c ) {
elem.className = elem.className.replace( classReg( c ), ' ' );
};
} | // full names
hasClass: hasClass,
addClass: addClass,
removeClass: removeClass,
// short names
has: hasClass,
add: addClass,
remove: removeClass
};
})( window ); |
window.classie = { | random_line_split |
classie.js | /*!
* classie - class helper functions
* from bonzo https://github.com/ded/bonzo
*
* classie.has( elem, 'my-class' ) -> true/false
* classie.add( elem, 'my-new-class' )
* classie.remove( elem, 'my-unwanted-class' )
*/
/*jshint browser: true, strict: true, undef: true */
( function( window ) {
'use strict';
// class helper functions from bonzo https://github.com/ded/bonzo
function | ( className ) {
return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
}
// classList support for class management
// altho to be fair, the api sucks because it won't accept multiple classes at once
var hasClass, addClass, removeClass;
if ( 'classList' in document.documentElement ) {
hasClass = function( elem, c ) {
return elem.classList.contains( c );
};
addClass = function( elem, c ) {
elem.classList.add( c );
};
removeClass = function( elem, c ) {
elem.classList.remove( c );
};
}
else {
hasClass = function( elem, c ) {
return classReg( c ).test( elem.className );
};
addClass = function( elem, c ) {
if ( !hasClass( elem, c ) ) {
elem.className = elem.className + ' ' + c;
}
};
removeClass = function( elem, c ) {
elem.className = elem.className.replace( classReg( c ), ' ' );
};
}
window.classie = {
// full names
hasClass: hasClass,
addClass: addClass,
removeClass: removeClass,
// short names
has: hasClass,
add: addClass,
remove: removeClass
};
})( window );
| classReg | identifier_name |
interface_config.js | /* eslint-disable no-unused-vars, no-var, max-len */
var interfaceConfig = {
// TO FIX: this needs to be handled from SASS variables. There are some
// methods allowing to use variables both in css and js.
DEFAULT_BACKGROUND: '#474747',
/**
* In case the desktop sharing is disabled through the config the button
* will not be hidden, but displayed as disabled with this text us as
* a tooltip.
*/
DESKTOP_SHARING_BUTTON_DISABLED_TOOLTIP: null,
INITIAL_TOOLBAR_TIMEOUT: 20000,
TOOLBAR_TIMEOUT: 4000,
TOOLBAR_ALWAYS_VISIBLE: false,
DEFAULT_REMOTE_DISPLAY_NAME: 'Fellow Jitster',
DEFAULT_LOCAL_DISPLAY_NAME: 'me',
SHOW_JITSI_WATERMARK: true,
JITSI_WATERMARK_LINK: 'https://jitsi.org',
// if watermark is disabled by default, it can be shown only for guests
SHOW_WATERMARK_FOR_GUESTS: true,
SHOW_BRAND_WATERMARK: false,
BRAND_WATERMARK_LINK: '',
SHOW_POWERED_BY: false,
SHOW_DEEP_LINKING_IMAGE: false,
GENERATE_ROOMNAMES_ON_WELCOME_PAGE: true,
DISPLAY_WELCOME_PAGE_CONTENT: true,
APP_NAME: 'Jitsi Meet',
NATIVE_APP_NAME: 'Jitsi Meet',
LANG_DETECTION: false, // Allow i18n to detect the system language
INVITATION_POWERED_BY: true,
/**
* If we should show authentication block in profile
*/
AUTHENTICATION_ENABLE: true,
/**
* The name of the toolbar buttons to display in the toolbar. If present,
* the button will display. Exceptions are "livestreaming" and "recording" | * enabled. Also, the "profile" button will not display for user's with a
* jwt.
*/
TOOLBAR_BUTTONS: [
'microphone', 'camera', 'desktop', 'fullscreen', 'fodeviceselection', 'hangup',
'profile', 'info', 'chat', 'recording', 'livestreaming', 'etherpad',
'sharedvideo', 'settings', 'raisehand', 'videoquality', 'filmstrip',
'invite', 'feedback', 'stats', 'shortcuts'
],
SETTINGS_SECTIONS: [ 'language', 'devices', 'moderator' ],
// Determines how the video would fit the screen. 'both' would fit the whole
// screen, 'height' would fit the original video height to the height of the
// screen, 'width' would fit the original video width to the width of the
// screen respecting ratio.
VIDEO_LAYOUT_FIT: 'both',
/**
* Whether to only show the filmstrip (and hide the toolbar).
*/
filmStripOnly: false,
/**
* Whether to show thumbnails in filmstrip as a column instead of as a row.
*/
VERTICAL_FILMSTRIP: true,
// A html text to be shown to guests on the close page, false disables it
CLOSE_PAGE_GUEST_HINT: false,
RANDOM_AVATAR_URL_PREFIX: false,
RANDOM_AVATAR_URL_SUFFIX: false,
FILM_STRIP_MAX_HEIGHT: 120,
// Enables feedback star animation.
ENABLE_FEEDBACK_ANIMATION: false,
DISABLE_FOCUS_INDICATOR: false,
DISABLE_DOMINANT_SPEAKER_INDICATOR: false,
/**
* Whether the ringing sound in the call/ring overlay is disabled. If
* {@code undefined}, defaults to {@code false}.
*
* @type {boolean}
*/
DISABLE_RINGING: false,
AUDIO_LEVEL_PRIMARY_COLOR: 'rgba(255,255,255,0.4)',
AUDIO_LEVEL_SECONDARY_COLOR: 'rgba(255,255,255,0.2)',
POLICY_LOGO: null,
LOCAL_THUMBNAIL_RATIO: 16 / 9, // 16:9
REMOTE_THUMBNAIL_RATIO: 1, // 1:1
// Documentation reference for the live streaming feature.
LIVE_STREAMING_HELP_LINK: 'https://jitsi.org/live',
/**
* Whether the mobile app Jitsi Meet is to be promoted to participants
* attempting to join a conference in a mobile Web browser. If
* {@code undefined}, defaults to {@code true}.
*
* @type {boolean}
*/
MOBILE_APP_PROMO: true,
/**
* Maximum coeficient of the ratio of the large video to the visible area
* after the large video is scaled to fit the window.
*
* @type {number}
*/
MAXIMUM_ZOOMING_COEFFICIENT: 1.3,
/*
* If indicated some of the error dialogs may point to the support URL for
* help.
*/
SUPPORT_URL: 'https://github.com/jitsi/jitsi-meet/issues/new',
/**
* Whether the connection indicator icon should hide itself based on
* connection strength. If true, the connection indicator will remain
* displayed while the participant has a weak connection and will hide
* itself after the CONNECTION_INDICATOR_HIDE_TIMEOUT when the connection is
* strong.
*
* @type {boolean}
*/
CONNECTION_INDICATOR_AUTO_HIDE_ENABLED: true,
/**
* How long the connection indicator should remain displayed before hiding.
* Used in conjunction with CONNECTION_INDICATOR_AUTOHIDE_ENABLED.
*
* @type {number}
*/
CONNECTION_INDICATOR_AUTO_HIDE_TIMEOUT: 5000,
/**
* The name of the application connected to the "Add people" search service.
*/
// ADD_PEOPLE_APP_NAME: "",
/**
* If true, hides the video quality label indicating the resolution status
* of the current large video.
*
* @type {boolean}
*/
VIDEO_QUALITY_LABEL_DISABLED: false,
/**
* Temporary feature flag to debug performance with the large video
* background blur. On initial implementation, blur was always enabled so a
* falsy value here will be used to keep blur enabled, as will the value
* "video", and will render the blur over a video element. The value
* "canvas" will display the blur over a canvas element, while the value
* "off" will prevent the background from rendering.
*/
_BACKGROUND_BLUR: 'off'
/**
* Specify custom URL for downloading android mobile app.
*/
// MOBILE_DOWNLOAD_LINK_ANDROID: 'https://play.google.com/store/apps/details?id=org.jitsi.meet',
/**
* Specify URL for downloading ios mobile app.
*/
// MOBILE_DOWNLOAD_LINK_IOS: 'https://itunes.apple.com/us/app/jitsi-meet/id1165103905',
/**
* Specify mobile app scheme for opening the app from the mobile browser.
*/
// APP_SCHEME: 'org.jitsi.meet'
};
/* eslint-enable no-unused-vars, no-var, max-len */ | * which also require being a moderator and some values in config.js to be | random_line_split |
BasePlayer.py |
import numpy as np
import cv2
from skimage.morphology import closing, erosion, opening
from pyKinectTools.algs.BackgroundSubtraction import *
class BasePlayer(object):
depthIm = None
colorIm = None
users = None
backgroundModel = None
foregroundMask = None
mask = None
prevcolorIm = None
def | (self, base_dir='./', get_depth=True, get_color=False,
get_skeleton=False, bg_subtraction=False, fill_images=False,
background_model=None, background_param=None):
self.base_dir = base_dir
self.deviceID = '[]'
if bg_subtraction and background_model is None:
raise Exception, "Must specify background_model"
self.get_depth = get_depth
self.get_color = get_color
self.get_skeleton =get_skeleton
self.enable_bg_subtraction = bg_subtraction
self.fill_images = fill_images
if background_model is not None:
print 'Setting up background model:', background_model
self.set_bg_model(background_model, background_param)
def update_background(self):
try:
self.background_model.update(self.depthIm)
self.mask = self.background_model.get_foreground()
# self.mask = self.get_person()
except:
self.mask = None
def set_background(self, im):
self.background_model.backgroundModel = im
def set_bg_model(self, bg_type='box', param=None):
'''
Types:
'box'[param=max_depth]
'static'[param=background]
'mean'
'median'
'adaptive_mog'
'''
self.enable_bg_subtraction = True
if bg_type == 'box':
self.bgSubtraction = BoxModel(param)
elif bg_type == 'static':
if param==None:
param = self.depthIm
self.bgSubtraction = StaticModel(depthIm=param)
elif bg_type == 'mean':
self.bgSubtraction = MeanModel(depthIm=self.depthIm)
elif bg_type == 'median':
self.bgSubtraction = MedianModel(depthIm=self.depthIm)
elif bg_type == 'adaptive_mog':
self.bgSubtraction = AdaptiveMixtureOfGaussians(self.depthIm, maxGaussians=5, learningRate=0.01, decayRate=0.001, variance=300**2)
else:
print "No background model added"
self.backgroundModel = self.bgSubtraction.getModel()
def next(self, frames=1):
pass
def get_person(self, edge_thresh=200):
mask, _, _, _ = extract_people(self.foregroundMask, minPersonPixThresh=5000, gradThresh=None)
# mask, _, _, _ = extract_people(self.mask, minPersonPixThresh=5000, gradThresh=None)
# mask, _, _, _ = extract_people(self.mask, minPersonPixThresh=5000, gradThresh=edge_thresh)
mask = erosion(mask, np.ones([3,3], np.uint8))
return mask
def visualize(self, color=True, depth=True, show_skel=False):
# ''' Find people '''
if show_skel:
plotUsers(self.depthIm, self.users)
if self.get_depth and depth:
cv2.imshow("Depth"+self.deviceID, (self.depthIm-1000)/float(self.depthIm.max()))
# cv2.putText(self.deviceID, (5,220), (255,255,255), size=15)
# vv.imshow("Depth", self.depthIm/6000.)
if self.get_color and color:
cv2.imshow("Color "+self.deviceID, self.colorIm/255.)
# vv.putText("Color "+self.deviceID, self.colorIm, "Day "+self.day_dir+" Time "+self.hour_dir+":"+self.minute_dir+" Dev#"+str(self.dev), (10,220))
# vv.imshow("Color", self.colorIm)
cv2.waitKey(10)
def run(self):
pass
| __init__ | identifier_name |
BasePlayer.py |
import numpy as np
import cv2
from skimage.morphology import closing, erosion, opening
from pyKinectTools.algs.BackgroundSubtraction import *
class BasePlayer(object):
depthIm = None
colorIm = None
users = None
backgroundModel = None
foregroundMask = None
mask = None
prevcolorIm = None
def __init__(self, base_dir='./', get_depth=True, get_color=False,
get_skeleton=False, bg_subtraction=False, fill_images=False,
background_model=None, background_param=None):
self.base_dir = base_dir
self.deviceID = '[]'
if bg_subtraction and background_model is None:
raise Exception, "Must specify background_model"
self.get_depth = get_depth
self.get_color = get_color
self.get_skeleton =get_skeleton
self.enable_bg_subtraction = bg_subtraction
self.fill_images = fill_images
if background_model is not None:
print 'Setting up background model:', background_model
self.set_bg_model(background_model, background_param)
def update_background(self):
try:
self.background_model.update(self.depthIm)
self.mask = self.background_model.get_foreground()
# self.mask = self.get_person()
except:
self.mask = None
def set_background(self, im):
self.background_model.backgroundModel = im
def set_bg_model(self, bg_type='box', param=None):
'''
Types:
'box'[param=max_depth]
'static'[param=background]
'mean'
'median'
'adaptive_mog'
'''
self.enable_bg_subtraction = True
if bg_type == 'box':
self.bgSubtraction = BoxModel(param)
elif bg_type == 'static':
if param==None:
|
self.bgSubtraction = StaticModel(depthIm=param)
elif bg_type == 'mean':
self.bgSubtraction = MeanModel(depthIm=self.depthIm)
elif bg_type == 'median':
self.bgSubtraction = MedianModel(depthIm=self.depthIm)
elif bg_type == 'adaptive_mog':
self.bgSubtraction = AdaptiveMixtureOfGaussians(self.depthIm, maxGaussians=5, learningRate=0.01, decayRate=0.001, variance=300**2)
else:
print "No background model added"
self.backgroundModel = self.bgSubtraction.getModel()
def next(self, frames=1):
pass
def get_person(self, edge_thresh=200):
mask, _, _, _ = extract_people(self.foregroundMask, minPersonPixThresh=5000, gradThresh=None)
# mask, _, _, _ = extract_people(self.mask, minPersonPixThresh=5000, gradThresh=None)
# mask, _, _, _ = extract_people(self.mask, minPersonPixThresh=5000, gradThresh=edge_thresh)
mask = erosion(mask, np.ones([3,3], np.uint8))
return mask
def visualize(self, color=True, depth=True, show_skel=False):
# ''' Find people '''
if show_skel:
plotUsers(self.depthIm, self.users)
if self.get_depth and depth:
cv2.imshow("Depth"+self.deviceID, (self.depthIm-1000)/float(self.depthIm.max()))
# cv2.putText(self.deviceID, (5,220), (255,255,255), size=15)
# vv.imshow("Depth", self.depthIm/6000.)
if self.get_color and color:
cv2.imshow("Color "+self.deviceID, self.colorIm/255.)
# vv.putText("Color "+self.deviceID, self.colorIm, "Day "+self.day_dir+" Time "+self.hour_dir+":"+self.minute_dir+" Dev#"+str(self.dev), (10,220))
# vv.imshow("Color", self.colorIm)
cv2.waitKey(10)
def run(self):
pass
| param = self.depthIm | conditional_block |
BasePlayer.py | import numpy as np
import cv2
from skimage.morphology import closing, erosion, opening
from pyKinectTools.algs.BackgroundSubtraction import *
class BasePlayer(object):
depthIm = None
colorIm = None
users = None
backgroundModel = None
foregroundMask = None
mask = None
prevcolorIm = None
def __init__(self, base_dir='./', get_depth=True, get_color=False,
get_skeleton=False, bg_subtraction=False, fill_images=False,
background_model=None, background_param=None):
self.base_dir = base_dir
self.deviceID = '[]'
if bg_subtraction and background_model is None:
raise Exception, "Must specify background_model"
self.get_depth = get_depth
self.get_color = get_color
self.get_skeleton =get_skeleton
self.enable_bg_subtraction = bg_subtraction
self.fill_images = fill_images
if background_model is not None:
print 'Setting up background model:', background_model
self.set_bg_model(background_model, background_param)
def update_background(self):
try:
self.background_model.update(self.depthIm)
self.mask = self.background_model.get_foreground()
# self.mask = self.get_person()
except:
self.mask = None
def set_background(self, im):
self.background_model.backgroundModel = im
def set_bg_model(self, bg_type='box', param=None):
'''
Types:
'box'[param=max_depth]
'static'[param=background]
'mean'
'median'
'adaptive_mog'
'''
self.enable_bg_subtraction = True
if bg_type == 'box':
self.bgSubtraction = BoxModel(param) | elif bg_type == 'static':
if param==None:
param = self.depthIm
self.bgSubtraction = StaticModel(depthIm=param)
elif bg_type == 'mean':
self.bgSubtraction = MeanModel(depthIm=self.depthIm)
elif bg_type == 'median':
self.bgSubtraction = MedianModel(depthIm=self.depthIm)
elif bg_type == 'adaptive_mog':
self.bgSubtraction = AdaptiveMixtureOfGaussians(self.depthIm, maxGaussians=5, learningRate=0.01, decayRate=0.001, variance=300**2)
else:
print "No background model added"
self.backgroundModel = self.bgSubtraction.getModel()
def next(self, frames=1):
pass
def get_person(self, edge_thresh=200):
mask, _, _, _ = extract_people(self.foregroundMask, minPersonPixThresh=5000, gradThresh=None)
# mask, _, _, _ = extract_people(self.mask, minPersonPixThresh=5000, gradThresh=None)
# mask, _, _, _ = extract_people(self.mask, minPersonPixThresh=5000, gradThresh=edge_thresh)
mask = erosion(mask, np.ones([3,3], np.uint8))
return mask
def visualize(self, color=True, depth=True, show_skel=False):
# ''' Find people '''
if show_skel:
plotUsers(self.depthIm, self.users)
if self.get_depth and depth:
cv2.imshow("Depth"+self.deviceID, (self.depthIm-1000)/float(self.depthIm.max()))
# cv2.putText(self.deviceID, (5,220), (255,255,255), size=15)
# vv.imshow("Depth", self.depthIm/6000.)
if self.get_color and color:
cv2.imshow("Color "+self.deviceID, self.colorIm/255.)
# vv.putText("Color "+self.deviceID, self.colorIm, "Day "+self.day_dir+" Time "+self.hour_dir+":"+self.minute_dir+" Dev#"+str(self.dev), (10,220))
# vv.imshow("Color", self.colorIm)
cv2.waitKey(10)
def run(self):
pass | random_line_split | |
BasePlayer.py |
import numpy as np
import cv2
from skimage.morphology import closing, erosion, opening
from pyKinectTools.algs.BackgroundSubtraction import *
class BasePlayer(object):
depthIm = None
colorIm = None
users = None
backgroundModel = None
foregroundMask = None
mask = None
prevcolorIm = None
def __init__(self, base_dir='./', get_depth=True, get_color=False,
get_skeleton=False, bg_subtraction=False, fill_images=False,
background_model=None, background_param=None):
self.base_dir = base_dir
self.deviceID = '[]'
if bg_subtraction and background_model is None:
raise Exception, "Must specify background_model"
self.get_depth = get_depth
self.get_color = get_color
self.get_skeleton =get_skeleton
self.enable_bg_subtraction = bg_subtraction
self.fill_images = fill_images
if background_model is not None:
print 'Setting up background model:', background_model
self.set_bg_model(background_model, background_param)
def update_background(self):
try:
self.background_model.update(self.depthIm)
self.mask = self.background_model.get_foreground()
# self.mask = self.get_person()
except:
self.mask = None
def set_background(self, im):
self.background_model.backgroundModel = im
def set_bg_model(self, bg_type='box', param=None):
'''
Types:
'box'[param=max_depth]
'static'[param=background]
'mean'
'median'
'adaptive_mog'
'''
self.enable_bg_subtraction = True
if bg_type == 'box':
self.bgSubtraction = BoxModel(param)
elif bg_type == 'static':
if param==None:
param = self.depthIm
self.bgSubtraction = StaticModel(depthIm=param)
elif bg_type == 'mean':
self.bgSubtraction = MeanModel(depthIm=self.depthIm)
elif bg_type == 'median':
self.bgSubtraction = MedianModel(depthIm=self.depthIm)
elif bg_type == 'adaptive_mog':
self.bgSubtraction = AdaptiveMixtureOfGaussians(self.depthIm, maxGaussians=5, learningRate=0.01, decayRate=0.001, variance=300**2)
else:
print "No background model added"
self.backgroundModel = self.bgSubtraction.getModel()
def next(self, frames=1):
pass
def get_person(self, edge_thresh=200):
mask, _, _, _ = extract_people(self.foregroundMask, minPersonPixThresh=5000, gradThresh=None)
# mask, _, _, _ = extract_people(self.mask, minPersonPixThresh=5000, gradThresh=None)
# mask, _, _, _ = extract_people(self.mask, minPersonPixThresh=5000, gradThresh=edge_thresh)
mask = erosion(mask, np.ones([3,3], np.uint8))
return mask
def visualize(self, color=True, depth=True, show_skel=False):
# ''' Find people '''
|
def run(self):
pass
| if show_skel:
plotUsers(self.depthIm, self.users)
if self.get_depth and depth:
cv2.imshow("Depth"+self.deviceID, (self.depthIm-1000)/float(self.depthIm.max()))
# cv2.putText(self.deviceID, (5,220), (255,255,255), size=15)
# vv.imshow("Depth", self.depthIm/6000.)
if self.get_color and color:
cv2.imshow("Color "+self.deviceID, self.colorIm/255.)
# vv.putText("Color "+self.deviceID, self.colorIm, "Day "+self.day_dir+" Time "+self.hour_dir+":"+self.minute_dir+" Dev#"+str(self.dev), (10,220))
# vv.imshow("Color", self.colorIm)
cv2.waitKey(10) | identifier_body |
cs.py | # $Id: cs.py 7119 2011-09-02 13:00:23Z milde $
# Author: Marek Blaha <mb@dat.cz>
# Copyright: This module has been placed in the public domain.
# New language mappings are welcome. Before doing a new translation, please
# read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be
# translated for each language: one in docutils/languages, the other in
# docutils/parsers/rst/languages.
"""
Czech-language mappings for language-dependent features of
reStructuredText.
"""
__docformat__ = 'reStructuredText'
directives = {
# language-dependent: fixed
u'pozor': 'attention',
u'caution (translation required)': 'caution', # jak rozlisit caution a warning?
u'code (translation required)': 'code',
u'nebezpe\u010D\u00ED': 'danger',
u'chyba': 'error',
u'rada': 'hint',
u'd\u016Fle\u017Eit\u00E9': 'important',
u'pozn\u00E1mka': 'note', | u'line-block (translation required)': 'line-block',
u'parsed-literal (translation required)': 'parsed-literal',
u'odd\u00EDl': 'rubric',
u'moto': 'epigraph',
u'highlights (translation required)': 'highlights',
u'pull-quote (translation required)': 'pull-quote',
u'compound (translation required)': 'compound',
u'container (translation required)': 'container',
#'questions': 'questions',
#'qa': 'questions',
#'faq': 'questions',
u'table (translation required)': 'table',
u'csv-table (translation required)': 'csv-table',
u'list-table (translation required)': 'list-table',
u'math (translation required)': 'math',
u'meta (translation required)': 'meta',
#'imagemap': 'imagemap',
u'image (translation required)': 'image', # obrazek
u'figure (translation required)': 'figure', # a tady?
u'include (translation required)': 'include',
u'raw (translation required)': 'raw',
u'replace (translation required)': 'replace',
u'unicode (translation required)': 'unicode',
u'datum': 'date',
u't\u0159\u00EDda': 'class',
u'role (translation required)': 'role',
u'default-role (translation required)': 'default-role',
u'title (translation required)': 'title',
u'obsah': 'contents',
u'sectnum (translation required)': 'sectnum',
u'section-numbering (translation required)': 'sectnum',
u'header (translation required)': 'header',
u'footer (translation required)': 'footer',
#'footnotes': 'footnotes',
#'citations': 'citations',
u'target-notes (translation required)': 'target-notes',
u'restructuredtext-test-directive': 'restructuredtext-test-directive'}
"""Czech name to registered (in directives/__init__.py) directive name
mapping."""
roles = {
# language-dependent: fixed
u'abbreviation (translation required)': 'abbreviation',
u'ab (translation required)': 'abbreviation',
u'acronym (translation required)': 'acronym',
u'ac (translation required)': 'acronym',
u'code (translation required)': 'code',
u'index (translation required)': 'index',
u'i (translation required)': 'index',
u'subscript (translation required)': 'subscript',
u'sub (translation required)': 'subscript',
u'superscript (translation required)': 'superscript',
u'sup (translation required)': 'superscript',
u'title-reference (translation required)': 'title-reference',
u'title (translation required)': 'title-reference',
u't (translation required)': 'title-reference',
u'pep-reference (translation required)': 'pep-reference',
u'pep (translation required)': 'pep-reference',
u'rfc-reference (translation required)': 'rfc-reference',
u'rfc (translation required)': 'rfc-reference',
u'emphasis (translation required)': 'emphasis',
u'strong (translation required)': 'strong',
u'literal (translation required)': 'literal',
u'math (translation required)': 'math',
u'named-reference (translation required)': 'named-reference',
u'anonymous-reference (translation required)': 'anonymous-reference',
u'footnote-reference (translation required)': 'footnote-reference',
u'citation-reference (translation required)': 'citation-reference',
u'substitution-reference (translation required)': 'substitution-reference',
u'target (translation required)': 'target',
u'uri-reference (translation required)': 'uri-reference',
u'uri (translation required)': 'uri-reference',
u'url (translation required)': 'uri-reference',
u'raw (translation required)': 'raw',}
"""Mapping of Czech role names to canonical role names for interpreted text.
""" | u'tip (translation required)': 'tip',
u'varov\u00E1n\u00ED': 'warning',
u'admonition (translation required)': 'admonition',
u'sidebar (translation required)': 'sidebar',
u't\u00E9ma': 'topic', | random_line_split |
recipes.py | from collections import defaultdict, namedtuple
from minecraft_data.v1_8 import recipes as raw_recipes
RecipeItem = namedtuple('RecipeItem', 'id meta amount')
class Recipe(object):
def __init__(self, raw):
self.result = reformat_item(raw['result'], None)
if 'ingredients' in raw:
self.ingredients = [reformat_item(item, 0)
for item in raw['ingredients']]
self.in_shape = None
self.out_shape = None
else:
self.in_shape = reformat_shape(raw['inShape'])
self.out_shape = reformat_shape(raw['outShape']) \
if 'outShape' in raw else None
self.ingredients = [item for row in self.in_shape for item in row]
@property
def total_ingredient_amounts(self):
"""
Returns:
dict: In the form { (item_id, metadata) -> amount }
"""
totals = defaultdict(int)
for id, meta, amount in self.ingredients:
totals[(id, meta)] += amount
return totals
@property
def ingredient_positions(self):
"""
Returns:
dict: In the form { (item_id, metadata) -> [(x, y, amount), ...] }
"""
positions = defaultdict(list)
for y, row in enumerate(self.in_shape):
for x, (item_id, metadata, amount) in enumerate(row):
positions[(item_id, metadata)].append((x, y, amount))
return positions
def reformat_item(raw, default_meta=None):
if isinstance(raw, dict):
raw = raw.copy() # do not modify arg
if 'metadata' not in raw:
raw['metadata'] = default_meta
if 'count' not in raw:
raw['count'] = 1
return RecipeItem(raw['id'], raw['metadata'], raw['count'])
elif isinstance(raw, list):
return RecipeItem(raw[0], raw[1], 1)
else: # single ID or None
return RecipeItem(raw or None, default_meta, 1)
def reformat_shape(shape):
return [[reformat_item(item, None) for item in row] for row in shape]
def iter_recipes(item_id, meta=None):
item_id = str(item_id)
meta = meta and int(meta)
try:
recipes_for_item = raw_recipes[item_id]
except KeyError:
return # no recipe found, do not yield anything | recipe = Recipe(raw)
if meta is None or meta == recipe.result.meta:
yield recipe
def get_any_recipe(item, meta=None):
# TODO return small recipes if present
for matching in iter_recipes(item, meta):
return matching
return None | else:
for raw in recipes_for_item: | random_line_split |
recipes.py | from collections import defaultdict, namedtuple
from minecraft_data.v1_8 import recipes as raw_recipes
RecipeItem = namedtuple('RecipeItem', 'id meta amount')
class Recipe(object):
def __init__(self, raw):
self.result = reformat_item(raw['result'], None)
if 'ingredients' in raw:
self.ingredients = [reformat_item(item, 0)
for item in raw['ingredients']]
self.in_shape = None
self.out_shape = None
else:
self.in_shape = reformat_shape(raw['inShape'])
self.out_shape = reformat_shape(raw['outShape']) \
if 'outShape' in raw else None
self.ingredients = [item for row in self.in_shape for item in row]
@property
def total_ingredient_amounts(self):
"""
Returns:
dict: In the form { (item_id, metadata) -> amount }
"""
totals = defaultdict(int)
for id, meta, amount in self.ingredients:
totals[(id, meta)] += amount
return totals
@property
def ingredient_positions(self):
"""
Returns:
dict: In the form { (item_id, metadata) -> [(x, y, amount), ...] }
"""
positions = defaultdict(list)
for y, row in enumerate(self.in_shape):
for x, (item_id, metadata, amount) in enumerate(row):
positions[(item_id, metadata)].append((x, y, amount))
return positions
def reformat_item(raw, default_meta=None):
|
def reformat_shape(shape):
return [[reformat_item(item, None) for item in row] for row in shape]
def iter_recipes(item_id, meta=None):
item_id = str(item_id)
meta = meta and int(meta)
try:
recipes_for_item = raw_recipes[item_id]
except KeyError:
return # no recipe found, do not yield anything
else:
for raw in recipes_for_item:
recipe = Recipe(raw)
if meta is None or meta == recipe.result.meta:
yield recipe
def get_any_recipe(item, meta=None):
# TODO return small recipes if present
for matching in iter_recipes(item, meta):
return matching
return None
| if isinstance(raw, dict):
raw = raw.copy() # do not modify arg
if 'metadata' not in raw:
raw['metadata'] = default_meta
if 'count' not in raw:
raw['count'] = 1
return RecipeItem(raw['id'], raw['metadata'], raw['count'])
elif isinstance(raw, list):
return RecipeItem(raw[0], raw[1], 1)
else: # single ID or None
return RecipeItem(raw or None, default_meta, 1) | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.