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
main.rs
extern crate piston; extern crate graphics; extern crate piston_window; extern crate time; extern crate rand; extern crate ai_behavior; extern crate cgmath; extern crate opengl_graphics; mod app; mod entitymanager; mod entity; mod system; mod player; mod config; mod person; mod personspawner; mod graphics_context; use entity::Entity; use graphics_context::GraphicsContext; use piston_window::{ PistonWindow, WindowSettings }; use piston::input::*; use piston::event_loop::*; use opengl_graphics::*; use rand::Rng; use cgmath::Vector2; fn main() { let mut rng = rand::thread_rng(); let seed: [u32;4] = [rng.gen::<u32>(), rng.gen::<u32>(), rng.gen::<u32>(), rng.gen::<u32>()]; let opengl = OpenGL::V3_2; let mut window: PistonWindow = WindowSettings::new("GGJ2016", [800, 600])
.unwrap_or_else(|e| { panic!("Failed to build PistonWindow: {}", e) }); window.set_ups(60); let mut background_textures :Vec<String> = Vec::new(); background_textures.push(String::from("assets/img/ground/placeholder_01.jpg")); background_textures.push(String::from("assets/img/ground/placeholder_02.jpg")); let mut gl = GlGraphics::new(opengl); let mut ctx = GraphicsContext::new(800, 600, seed, background_textures); ctx.load_textures(); let player_tex = String::from("assets/img/emoji/78.png"); let person_tex = String::from("assets/img/emoji/77.png"); ctx.load_texture(&player_tex); ctx.load_texture(&person_tex); ctx.load_texture(&String::from("assets/img/emoji/33.png")); let mut app = app::App::new(player_tex); app.add_system(Box::new(personspawner::PersonSpawner::new())); app.add_entity(Box::new(person::Person::new(person_tex, Vector2::new(50.0, 50.0)))); // Add player to entities (player instanciated in app) //app.add_entity(Box::new(player::Player::new())); for e in window { if let Some(args) = e.press_args() { app.key_press(args); } if let Some(args) = e.release_args() { app.key_release(args); } if let Some(args) = e.update_args() { app.update(args); } ctx.update_translation(app.get_player().get_position().x as u32, app.get_player().get_position().y as u32); if let Some(args) = e.render_args() { gl.draw(args.viewport(), |c, gl| { ctx.render(args, c, gl); app.render(&mut ctx, c, gl); }); } } }
.exit_on_esc(true) .opengl(opengl) .build()
random_line_split
main.rs
extern crate piston; extern crate graphics; extern crate piston_window; extern crate time; extern crate rand; extern crate ai_behavior; extern crate cgmath; extern crate opengl_graphics; mod app; mod entitymanager; mod entity; mod system; mod player; mod config; mod person; mod personspawner; mod graphics_context; use entity::Entity; use graphics_context::GraphicsContext; use piston_window::{ PistonWindow, WindowSettings }; use piston::input::*; use piston::event_loop::*; use opengl_graphics::*; use rand::Rng; use cgmath::Vector2; fn
() { let mut rng = rand::thread_rng(); let seed: [u32;4] = [rng.gen::<u32>(), rng.gen::<u32>(), rng.gen::<u32>(), rng.gen::<u32>()]; let opengl = OpenGL::V3_2; let mut window: PistonWindow = WindowSettings::new("GGJ2016", [800, 600]) .exit_on_esc(true) .opengl(opengl) .build() .unwrap_or_else(|e| { panic!("Failed to build PistonWindow: {}", e) }); window.set_ups(60); let mut background_textures :Vec<String> = Vec::new(); background_textures.push(String::from("assets/img/ground/placeholder_01.jpg")); background_textures.push(String::from("assets/img/ground/placeholder_02.jpg")); let mut gl = GlGraphics::new(opengl); let mut ctx = GraphicsContext::new(800, 600, seed, background_textures); ctx.load_textures(); let player_tex = String::from("assets/img/emoji/78.png"); let person_tex = String::from("assets/img/emoji/77.png"); ctx.load_texture(&player_tex); ctx.load_texture(&person_tex); ctx.load_texture(&String::from("assets/img/emoji/33.png")); let mut app = app::App::new(player_tex); app.add_system(Box::new(personspawner::PersonSpawner::new())); app.add_entity(Box::new(person::Person::new(person_tex, Vector2::new(50.0, 50.0)))); // Add player to entities (player instanciated in app) //app.add_entity(Box::new(player::Player::new())); for e in window { if let Some(args) = e.press_args() { app.key_press(args); } if let Some(args) = e.release_args() { app.key_release(args); } if let Some(args) = e.update_args() { app.update(args); } ctx.update_translation(app.get_player().get_position().x as u32, app.get_player().get_position().y as u32); if let Some(args) = e.render_args() { gl.draw(args.viewport(), |c, gl| { ctx.render(args, c, gl); app.render(&mut ctx, c, gl); }); } } }
main
identifier_name
main.rs
extern crate piston; extern crate graphics; extern crate piston_window; extern crate time; extern crate rand; extern crate ai_behavior; extern crate cgmath; extern crate opengl_graphics; mod app; mod entitymanager; mod entity; mod system; mod player; mod config; mod person; mod personspawner; mod graphics_context; use entity::Entity; use graphics_context::GraphicsContext; use piston_window::{ PistonWindow, WindowSettings }; use piston::input::*; use piston::event_loop::*; use opengl_graphics::*; use rand::Rng; use cgmath::Vector2; fn main()
{ let mut rng = rand::thread_rng(); let seed: [u32;4] = [rng.gen::<u32>(), rng.gen::<u32>(), rng.gen::<u32>(), rng.gen::<u32>()]; let opengl = OpenGL::V3_2; let mut window: PistonWindow = WindowSettings::new("GGJ2016", [800, 600]) .exit_on_esc(true) .opengl(opengl) .build() .unwrap_or_else(|e| { panic!("Failed to build PistonWindow: {}", e) }); window.set_ups(60); let mut background_textures :Vec<String> = Vec::new(); background_textures.push(String::from("assets/img/ground/placeholder_01.jpg")); background_textures.push(String::from("assets/img/ground/placeholder_02.jpg")); let mut gl = GlGraphics::new(opengl); let mut ctx = GraphicsContext::new(800, 600, seed, background_textures); ctx.load_textures(); let player_tex = String::from("assets/img/emoji/78.png"); let person_tex = String::from("assets/img/emoji/77.png"); ctx.load_texture(&player_tex); ctx.load_texture(&person_tex); ctx.load_texture(&String::from("assets/img/emoji/33.png")); let mut app = app::App::new(player_tex); app.add_system(Box::new(personspawner::PersonSpawner::new())); app.add_entity(Box::new(person::Person::new(person_tex, Vector2::new(50.0, 50.0)))); // Add player to entities (player instanciated in app) //app.add_entity(Box::new(player::Player::new())); for e in window { if let Some(args) = e.press_args() { app.key_press(args); } if let Some(args) = e.release_args() { app.key_release(args); } if let Some(args) = e.update_args() { app.update(args); } ctx.update_translation(app.get_player().get_position().x as u32, app.get_player().get_position().y as u32); if let Some(args) = e.render_args() { gl.draw(args.viewport(), |c, gl| { ctx.render(args, c, gl); app.render(&mut ctx, c, gl); }); } } }
identifier_body
main.rs
extern crate piston; extern crate graphics; extern crate piston_window; extern crate time; extern crate rand; extern crate ai_behavior; extern crate cgmath; extern crate opengl_graphics; mod app; mod entitymanager; mod entity; mod system; mod player; mod config; mod person; mod personspawner; mod graphics_context; use entity::Entity; use graphics_context::GraphicsContext; use piston_window::{ PistonWindow, WindowSettings }; use piston::input::*; use piston::event_loop::*; use opengl_graphics::*; use rand::Rng; use cgmath::Vector2; fn main() { let mut rng = rand::thread_rng(); let seed: [u32;4] = [rng.gen::<u32>(), rng.gen::<u32>(), rng.gen::<u32>(), rng.gen::<u32>()]; let opengl = OpenGL::V3_2; let mut window: PistonWindow = WindowSettings::new("GGJ2016", [800, 600]) .exit_on_esc(true) .opengl(opengl) .build() .unwrap_or_else(|e| { panic!("Failed to build PistonWindow: {}", e) }); window.set_ups(60); let mut background_textures :Vec<String> = Vec::new(); background_textures.push(String::from("assets/img/ground/placeholder_01.jpg")); background_textures.push(String::from("assets/img/ground/placeholder_02.jpg")); let mut gl = GlGraphics::new(opengl); let mut ctx = GraphicsContext::new(800, 600, seed, background_textures); ctx.load_textures(); let player_tex = String::from("assets/img/emoji/78.png"); let person_tex = String::from("assets/img/emoji/77.png"); ctx.load_texture(&player_tex); ctx.load_texture(&person_tex); ctx.load_texture(&String::from("assets/img/emoji/33.png")); let mut app = app::App::new(player_tex); app.add_system(Box::new(personspawner::PersonSpawner::new())); app.add_entity(Box::new(person::Person::new(person_tex, Vector2::new(50.0, 50.0)))); // Add player to entities (player instanciated in app) //app.add_entity(Box::new(player::Player::new())); for e in window { if let Some(args) = e.press_args()
if let Some(args) = e.release_args() { app.key_release(args); } if let Some(args) = e.update_args() { app.update(args); } ctx.update_translation(app.get_player().get_position().x as u32, app.get_player().get_position().y as u32); if let Some(args) = e.render_args() { gl.draw(args.viewport(), |c, gl| { ctx.render(args, c, gl); app.render(&mut ctx, c, gl); }); } } }
{ app.key_press(args); }
conditional_block
index.js
"use strict"; exports.__esModule = true; exports.default = void 0; var React = _interopRequireWildcard(require("react")); var _createElement = _interopRequireDefault(require("../createElement")); var _useMergeRefs = _interopRequireDefault(require("../../modules/useMergeRefs")); var _usePlatformMethods = _interopRequireDefault(require("../../modules/usePlatformMethods")); var _PickerItem = _interopRequireDefault(require("./PickerItem")); var _StyleSheet = _interopRequireDefault(require("../StyleSheet")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } var Picker = /*#__PURE__*/React.forwardRef(function (props, forwardedRef) { var children = props.children, enabled = props.enabled, onValueChange = props.onValueChange, selectedValue = props.selectedValue, style = props.style, testID = props.testID, itemStyle = props.itemStyle, mode = props.mode, prompt = props.prompt, other = _objectWithoutPropertiesLoose(props, ["children", "enabled", "onValueChange", "selectedValue", "style", "testID", "itemStyle", "mode", "prompt"]); var hostRef = React.useRef(null); function handleChange(e) { var _e$target = e.target, selectedIndex = _e$target.selectedIndex, value = _e$target.value;
if (onValueChange) { onValueChange(value, selectedIndex); } } // $FlowFixMe var supportedProps = _objectSpread({ children: children, disabled: enabled === false ? true : undefined, onChange: handleChange, style: [styles.initial, style], testID: testID, value: selectedValue }, other); var platformMethodsRef = (0, _usePlatformMethods.default)(supportedProps); var setRef = (0, _useMergeRefs.default)(hostRef, platformMethodsRef, forwardedRef); supportedProps.ref = setRef; return (0, _createElement.default)('select', supportedProps); }); // $FlowFixMe Picker.Item = _PickerItem.default; var styles = _StyleSheet.default.create({ initial: { fontFamily: 'System', fontSize: 'inherit', margin: 0 } }); var _default = Picker; exports.default = _default; module.exports = exports.default;
random_line_split
index.js
"use strict"; exports.__esModule = true; exports.default = void 0; var React = _interopRequireWildcard(require("react")); var _createElement = _interopRequireDefault(require("../createElement")); var _useMergeRefs = _interopRequireDefault(require("../../modules/useMergeRefs")); var _usePlatformMethods = _interopRequireDefault(require("../../modules/usePlatformMethods")); var _PickerItem = _interopRequireDefault(require("./PickerItem")); var _StyleSheet = _interopRequireDefault(require("../StyleSheet")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function
(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } var Picker = /*#__PURE__*/React.forwardRef(function (props, forwardedRef) { var children = props.children, enabled = props.enabled, onValueChange = props.onValueChange, selectedValue = props.selectedValue, style = props.style, testID = props.testID, itemStyle = props.itemStyle, mode = props.mode, prompt = props.prompt, other = _objectWithoutPropertiesLoose(props, ["children", "enabled", "onValueChange", "selectedValue", "style", "testID", "itemStyle", "mode", "prompt"]); var hostRef = React.useRef(null); function handleChange(e) { var _e$target = e.target, selectedIndex = _e$target.selectedIndex, value = _e$target.value; if (onValueChange) { onValueChange(value, selectedIndex); } } // $FlowFixMe var supportedProps = _objectSpread({ children: children, disabled: enabled === false ? true : undefined, onChange: handleChange, style: [styles.initial, style], testID: testID, value: selectedValue }, other); var platformMethodsRef = (0, _usePlatformMethods.default)(supportedProps); var setRef = (0, _useMergeRefs.default)(hostRef, platformMethodsRef, forwardedRef); supportedProps.ref = setRef; return (0, _createElement.default)('select', supportedProps); }); // $FlowFixMe Picker.Item = _PickerItem.default; var styles = _StyleSheet.default.create({ initial: { fontFamily: 'System', fontSize: 'inherit', margin: 0 } }); var _default = Picker; exports.default = _default; module.exports = exports.default;
_objectSpread
identifier_name
index.js
"use strict"; exports.__esModule = true; exports.default = void 0; var React = _interopRequireWildcard(require("react")); var _createElement = _interopRequireDefault(require("../createElement")); var _useMergeRefs = _interopRequireDefault(require("../../modules/useMergeRefs")); var _usePlatformMethods = _interopRequireDefault(require("../../modules/usePlatformMethods")); var _PickerItem = _interopRequireDefault(require("./PickerItem")); var _StyleSheet = _interopRequireDefault(require("../StyleSheet")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty(obj, key, value) { if (key in obj)
else { obj[key] = value; } return obj; } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } var Picker = /*#__PURE__*/React.forwardRef(function (props, forwardedRef) { var children = props.children, enabled = props.enabled, onValueChange = props.onValueChange, selectedValue = props.selectedValue, style = props.style, testID = props.testID, itemStyle = props.itemStyle, mode = props.mode, prompt = props.prompt, other = _objectWithoutPropertiesLoose(props, ["children", "enabled", "onValueChange", "selectedValue", "style", "testID", "itemStyle", "mode", "prompt"]); var hostRef = React.useRef(null); function handleChange(e) { var _e$target = e.target, selectedIndex = _e$target.selectedIndex, value = _e$target.value; if (onValueChange) { onValueChange(value, selectedIndex); } } // $FlowFixMe var supportedProps = _objectSpread({ children: children, disabled: enabled === false ? true : undefined, onChange: handleChange, style: [styles.initial, style], testID: testID, value: selectedValue }, other); var platformMethodsRef = (0, _usePlatformMethods.default)(supportedProps); var setRef = (0, _useMergeRefs.default)(hostRef, platformMethodsRef, forwardedRef); supportedProps.ref = setRef; return (0, _createElement.default)('select', supportedProps); }); // $FlowFixMe Picker.Item = _PickerItem.default; var styles = _StyleSheet.default.create({ initial: { fontFamily: 'System', fontSize: 'inherit', margin: 0 } }); var _default = Picker; exports.default = _default; module.exports = exports.default;
{ Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); }
conditional_block
index.js
"use strict"; exports.__esModule = true; exports.default = void 0; var React = _interopRequireWildcard(require("react")); var _createElement = _interopRequireDefault(require("../createElement")); var _useMergeRefs = _interopRequireDefault(require("../../modules/useMergeRefs")); var _usePlatformMethods = _interopRequireDefault(require("../../modules/usePlatformMethods")); var _PickerItem = _interopRequireDefault(require("./PickerItem")); var _StyleSheet = _interopRequireDefault(require("../StyleSheet")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } var Picker = /*#__PURE__*/React.forwardRef(function (props, forwardedRef) { var children = props.children, enabled = props.enabled, onValueChange = props.onValueChange, selectedValue = props.selectedValue, style = props.style, testID = props.testID, itemStyle = props.itemStyle, mode = props.mode, prompt = props.prompt, other = _objectWithoutPropertiesLoose(props, ["children", "enabled", "onValueChange", "selectedValue", "style", "testID", "itemStyle", "mode", "prompt"]); var hostRef = React.useRef(null); function handleChange(e)
var supportedProps = _objectSpread({ children: children, disabled: enabled === false ? true : undefined, onChange: handleChange, style: [styles.initial, style], testID: testID, value: selectedValue }, other); var platformMethodsRef = (0, _usePlatformMethods.default)(supportedProps); var setRef = (0, _useMergeRefs.default)(hostRef, platformMethodsRef, forwardedRef); supportedProps.ref = setRef; return (0, _createElement.default)('select', supportedProps); }); // $FlowFixMe Picker.Item = _PickerItem.default; var styles = _StyleSheet.default.create({ initial: { fontFamily: 'System', fontSize: 'inherit', margin: 0 } }); var _default = Picker; exports.default = _default; module.exports = exports.default;
{ var _e$target = e.target, selectedIndex = _e$target.selectedIndex, value = _e$target.value; if (onValueChange) { onValueChange(value, selectedIndex); } } // $FlowFixMe
identifier_body
mergeProcedureVirtual.py
# Serial Photo Merge # Copyright (C) 2017 Simone Riva mail: simone.rva {at} gmail {dot} com # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or #(at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import numpy as np import sys import scipy.ndimage as ndimage from imgmerge.readImg import ReadImageBasic from imgmerge.image import Image from imgmerge.readImgFactory import ReadImageFarctory #import matplotlib.pyplot as plt def get_dtype(color_bits): if color_bits == 8: return np.uint8 elif color_bits == 16: return np.uint16 class MergeProcedureVirtual(object): def __init__(self): self._img_list = None self._resimg = None self._refimage = None self._images_iterator = None self._read_img_factory = ReadImageFarctory() def set_images_iterator(self, img_itr): self._images_iterator = img_itr self._images_iterator.read_image_factory = self.read_image_factory def get_images_iterator(self): return self._images_iterator images_iterator = property(get_images_iterator, set_images_iterator) def set_images_list(self, img_list): self._img_list = img_list def get_images_list(self): return self._img_list images_list = property(get_images_list, set_images_list) def set_reference_image(self, file_name): self._refimage = file_name def get_reference_image(self): return self._refimage reference_image = property(get_reference_image, set_reference_image) def get_read_image_factory(self): return self._read_img_factory def
(self, rif): self._read_img_factory = rif if self.images_iterator: self.images_iterator.read_image_factory = rif read_image_factory = property( get_read_image_factory, set_read_image_factory) def execute(self): NotImplementedError( " %s : is virutal and must be overridden." % sys._getframe().f_code.co_name) def get_resulting_image(self): return self._resimg def set_resulting_image(self, resarr): self._resimg = resarr resulting_image = property(get_resulting_image, set_resulting_image)
set_read_image_factory
identifier_name
mergeProcedureVirtual.py
# Serial Photo Merge # Copyright (C) 2017 Simone Riva mail: simone.rva {at} gmail {dot} com # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or #(at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import numpy as np import sys import scipy.ndimage as ndimage from imgmerge.readImg import ReadImageBasic from imgmerge.image import Image from imgmerge.readImgFactory import ReadImageFarctory #import matplotlib.pyplot as plt def get_dtype(color_bits):
class MergeProcedureVirtual(object): def __init__(self): self._img_list = None self._resimg = None self._refimage = None self._images_iterator = None self._read_img_factory = ReadImageFarctory() def set_images_iterator(self, img_itr): self._images_iterator = img_itr self._images_iterator.read_image_factory = self.read_image_factory def get_images_iterator(self): return self._images_iterator images_iterator = property(get_images_iterator, set_images_iterator) def set_images_list(self, img_list): self._img_list = img_list def get_images_list(self): return self._img_list images_list = property(get_images_list, set_images_list) def set_reference_image(self, file_name): self._refimage = file_name def get_reference_image(self): return self._refimage reference_image = property(get_reference_image, set_reference_image) def get_read_image_factory(self): return self._read_img_factory def set_read_image_factory(self, rif): self._read_img_factory = rif if self.images_iterator: self.images_iterator.read_image_factory = rif read_image_factory = property( get_read_image_factory, set_read_image_factory) def execute(self): NotImplementedError( " %s : is virutal and must be overridden." % sys._getframe().f_code.co_name) def get_resulting_image(self): return self._resimg def set_resulting_image(self, resarr): self._resimg = resarr resulting_image = property(get_resulting_image, set_resulting_image)
if color_bits == 8: return np.uint8 elif color_bits == 16: return np.uint16
identifier_body
mergeProcedureVirtual.py
# Serial Photo Merge # Copyright (C) 2017 Simone Riva mail: simone.rva {at} gmail {dot} com # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or #(at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import numpy as np import sys import scipy.ndimage as ndimage from imgmerge.readImg import ReadImageBasic from imgmerge.image import Image from imgmerge.readImgFactory import ReadImageFarctory #import matplotlib.pyplot as plt def get_dtype(color_bits): if color_bits == 8: return np.uint8 elif color_bits == 16: return np.uint16 class MergeProcedureVirtual(object): def __init__(self): self._img_list = None self._resimg = None self._refimage = None self._images_iterator = None self._read_img_factory = ReadImageFarctory() def set_images_iterator(self, img_itr): self._images_iterator = img_itr self._images_iterator.read_image_factory = self.read_image_factory def get_images_iterator(self): return self._images_iterator images_iterator = property(get_images_iterator, set_images_iterator) def set_images_list(self, img_list): self._img_list = img_list def get_images_list(self): return self._img_list images_list = property(get_images_list, set_images_list) def set_reference_image(self, file_name): self._refimage = file_name def get_reference_image(self): return self._refimage reference_image = property(get_reference_image, set_reference_image) def get_read_image_factory(self): return self._read_img_factory def set_read_image_factory(self, rif): self._read_img_factory = rif if self.images_iterator: self.images_iterator.read_image_factory = rif read_image_factory = property( get_read_image_factory, set_read_image_factory)
def get_resulting_image(self): return self._resimg def set_resulting_image(self, resarr): self._resimg = resarr resulting_image = property(get_resulting_image, set_resulting_image)
def execute(self): NotImplementedError( " %s : is virutal and must be overridden." % sys._getframe().f_code.co_name)
random_line_split
mergeProcedureVirtual.py
# Serial Photo Merge # Copyright (C) 2017 Simone Riva mail: simone.rva {at} gmail {dot} com # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or #(at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import numpy as np import sys import scipy.ndimage as ndimage from imgmerge.readImg import ReadImageBasic from imgmerge.image import Image from imgmerge.readImgFactory import ReadImageFarctory #import matplotlib.pyplot as plt def get_dtype(color_bits): if color_bits == 8: return np.uint8 elif color_bits == 16:
class MergeProcedureVirtual(object): def __init__(self): self._img_list = None self._resimg = None self._refimage = None self._images_iterator = None self._read_img_factory = ReadImageFarctory() def set_images_iterator(self, img_itr): self._images_iterator = img_itr self._images_iterator.read_image_factory = self.read_image_factory def get_images_iterator(self): return self._images_iterator images_iterator = property(get_images_iterator, set_images_iterator) def set_images_list(self, img_list): self._img_list = img_list def get_images_list(self): return self._img_list images_list = property(get_images_list, set_images_list) def set_reference_image(self, file_name): self._refimage = file_name def get_reference_image(self): return self._refimage reference_image = property(get_reference_image, set_reference_image) def get_read_image_factory(self): return self._read_img_factory def set_read_image_factory(self, rif): self._read_img_factory = rif if self.images_iterator: self.images_iterator.read_image_factory = rif read_image_factory = property( get_read_image_factory, set_read_image_factory) def execute(self): NotImplementedError( " %s : is virutal and must be overridden." % sys._getframe().f_code.co_name) def get_resulting_image(self): return self._resimg def set_resulting_image(self, resarr): self._resimg = resarr resulting_image = property(get_resulting_image, set_resulting_image)
return np.uint16
conditional_block
ziptuple.rs
use super::size_hint; /// See [`multizip`](../fn.multizip.html) for more information. #[derive(Clone)] pub struct Zip<T> { t: T,
#[deprecated(note = "Renamed to multizip")] pub fn new<U>(t: U) -> Zip<T> where Zip<T>: From<U>, Zip<T>: Iterator, { multizip(t) } } /// An iterator that generalizes *.zip()* and allows running multiple iterators in lockstep. /// /// The iterator `Zip<(I, J, ..., M)>` is formed from a tuple of iterators (or values that /// implement `IntoIterator`) and yields elements /// until any of the subiterators yields `None`. /// /// The iterator element type is a tuple like like `(A, B, ..., E)` where `A` to `E` are the /// element types of the subiterator. /// /// ``` /// use itertools::multizip; /// /// // Iterate over three sequences side-by-side /// let mut xs = [0, 0, 0]; /// let ys = [69, 107, 101]; /// /// for (i, a, b) in multizip((0..100, &mut xs, &ys)) { /// *a = i ^ *b; /// } /// /// assert_eq!(xs, [69, 106, 103]); /// ``` pub fn multizip<T, U>(t: U) -> Zip<T> where Zip<T>: From<U>, Zip<T>: Iterator, { Zip::from(t) } macro_rules! impl_zip_iter { ($($B:ident),*) => ( #[allow(non_snake_case)] impl<$($B: IntoIterator),*> From<($($B,)*)> for Zip<($($B::IntoIter,)*)> { fn from(t: ($($B,)*)) -> Self { let ($($B,)*) = t; Zip { t: ($($B.into_iter(),)*) } } } #[allow(non_snake_case)] #[allow(unused_assignments)] impl<$($B),*> Iterator for Zip<($($B,)*)> where $( $B: Iterator, )* { type Item = ($($B::Item,)*); fn next(&mut self) -> Option<Self::Item> { let ($(ref mut $B,)*) = self.t; // NOTE: Just like iter::Zip, we check the iterators // for None in order. We may finish unevenly (some // iterators gave n + 1 elements, some only n). $( let $B = match $B.next() { None => return None, Some(elt) => elt }; )* Some(($($B,)*)) } fn size_hint(&self) -> (usize, Option<usize>) { let sh = (::std::usize::MAX, None); let ($(ref $B,)*) = self.t; $( let sh = size_hint::min($B.size_hint(), sh); )* sh } } #[allow(non_snake_case)] impl<$($B),*> ExactSizeIterator for Zip<($($B,)*)> where $( $B: ExactSizeIterator, )* { } ); } impl_zip_iter!(A); impl_zip_iter!(A, B); impl_zip_iter!(A, B, C); impl_zip_iter!(A, B, C, D); impl_zip_iter!(A, B, C, D, E); impl_zip_iter!(A, B, C, D, E, F); impl_zip_iter!(A, B, C, D, E, F, G); impl_zip_iter!(A, B, C, D, E, F, G, H);
} impl<T> Zip<T> { /// Deprecated: renamed to multizip
random_line_split
ziptuple.rs
use super::size_hint; /// See [`multizip`](../fn.multizip.html) for more information. #[derive(Clone)] pub struct Zip<T> { t: T, } impl<T> Zip<T> { /// Deprecated: renamed to multizip #[deprecated(note = "Renamed to multizip")] pub fn new<U>(t: U) -> Zip<T> where Zip<T>: From<U>, Zip<T>: Iterator,
} /// An iterator that generalizes *.zip()* and allows running multiple iterators in lockstep. /// /// The iterator `Zip<(I, J, ..., M)>` is formed from a tuple of iterators (or values that /// implement `IntoIterator`) and yields elements /// until any of the subiterators yields `None`. /// /// The iterator element type is a tuple like like `(A, B, ..., E)` where `A` to `E` are the /// element types of the subiterator. /// /// ``` /// use itertools::multizip; /// /// // Iterate over three sequences side-by-side /// let mut xs = [0, 0, 0]; /// let ys = [69, 107, 101]; /// /// for (i, a, b) in multizip((0..100, &mut xs, &ys)) { /// *a = i ^ *b; /// } /// /// assert_eq!(xs, [69, 106, 103]); /// ``` pub fn multizip<T, U>(t: U) -> Zip<T> where Zip<T>: From<U>, Zip<T>: Iterator, { Zip::from(t) } macro_rules! impl_zip_iter { ($($B:ident),*) => ( #[allow(non_snake_case)] impl<$($B: IntoIterator),*> From<($($B,)*)> for Zip<($($B::IntoIter,)*)> { fn from(t: ($($B,)*)) -> Self { let ($($B,)*) = t; Zip { t: ($($B.into_iter(),)*) } } } #[allow(non_snake_case)] #[allow(unused_assignments)] impl<$($B),*> Iterator for Zip<($($B,)*)> where $( $B: Iterator, )* { type Item = ($($B::Item,)*); fn next(&mut self) -> Option<Self::Item> { let ($(ref mut $B,)*) = self.t; // NOTE: Just like iter::Zip, we check the iterators // for None in order. We may finish unevenly (some // iterators gave n + 1 elements, some only n). $( let $B = match $B.next() { None => return None, Some(elt) => elt }; )* Some(($($B,)*)) } fn size_hint(&self) -> (usize, Option<usize>) { let sh = (::std::usize::MAX, None); let ($(ref $B,)*) = self.t; $( let sh = size_hint::min($B.size_hint(), sh); )* sh } } #[allow(non_snake_case)] impl<$($B),*> ExactSizeIterator for Zip<($($B,)*)> where $( $B: ExactSizeIterator, )* { } ); } impl_zip_iter!(A); impl_zip_iter!(A, B); impl_zip_iter!(A, B, C); impl_zip_iter!(A, B, C, D); impl_zip_iter!(A, B, C, D, E); impl_zip_iter!(A, B, C, D, E, F); impl_zip_iter!(A, B, C, D, E, F, G); impl_zip_iter!(A, B, C, D, E, F, G, H);
{ multizip(t) }
identifier_body
ziptuple.rs
use super::size_hint; /// See [`multizip`](../fn.multizip.html) for more information. #[derive(Clone)] pub struct Zip<T> { t: T, } impl<T> Zip<T> { /// Deprecated: renamed to multizip #[deprecated(note = "Renamed to multizip")] pub fn
<U>(t: U) -> Zip<T> where Zip<T>: From<U>, Zip<T>: Iterator, { multizip(t) } } /// An iterator that generalizes *.zip()* and allows running multiple iterators in lockstep. /// /// The iterator `Zip<(I, J, ..., M)>` is formed from a tuple of iterators (or values that /// implement `IntoIterator`) and yields elements /// until any of the subiterators yields `None`. /// /// The iterator element type is a tuple like like `(A, B, ..., E)` where `A` to `E` are the /// element types of the subiterator. /// /// ``` /// use itertools::multizip; /// /// // Iterate over three sequences side-by-side /// let mut xs = [0, 0, 0]; /// let ys = [69, 107, 101]; /// /// for (i, a, b) in multizip((0..100, &mut xs, &ys)) { /// *a = i ^ *b; /// } /// /// assert_eq!(xs, [69, 106, 103]); /// ``` pub fn multizip<T, U>(t: U) -> Zip<T> where Zip<T>: From<U>, Zip<T>: Iterator, { Zip::from(t) } macro_rules! impl_zip_iter { ($($B:ident),*) => ( #[allow(non_snake_case)] impl<$($B: IntoIterator),*> From<($($B,)*)> for Zip<($($B::IntoIter,)*)> { fn from(t: ($($B,)*)) -> Self { let ($($B,)*) = t; Zip { t: ($($B.into_iter(),)*) } } } #[allow(non_snake_case)] #[allow(unused_assignments)] impl<$($B),*> Iterator for Zip<($($B,)*)> where $( $B: Iterator, )* { type Item = ($($B::Item,)*); fn next(&mut self) -> Option<Self::Item> { let ($(ref mut $B,)*) = self.t; // NOTE: Just like iter::Zip, we check the iterators // for None in order. We may finish unevenly (some // iterators gave n + 1 elements, some only n). $( let $B = match $B.next() { None => return None, Some(elt) => elt }; )* Some(($($B,)*)) } fn size_hint(&self) -> (usize, Option<usize>) { let sh = (::std::usize::MAX, None); let ($(ref $B,)*) = self.t; $( let sh = size_hint::min($B.size_hint(), sh); )* sh } } #[allow(non_snake_case)] impl<$($B),*> ExactSizeIterator for Zip<($($B,)*)> where $( $B: ExactSizeIterator, )* { } ); } impl_zip_iter!(A); impl_zip_iter!(A, B); impl_zip_iter!(A, B, C); impl_zip_iter!(A, B, C, D); impl_zip_iter!(A, B, C, D, E); impl_zip_iter!(A, B, C, D, E, F); impl_zip_iter!(A, B, C, D, E, F, G); impl_zip_iter!(A, B, C, D, E, F, G, H);
new
identifier_name
stix-text-array.component.ts
import { Component, Input } from '@angular/core'; import { FormControl } from '@angular/forms'; @Component({ selector: 'stix-text-array', templateUrl: './stix-text-array.component.html' }) export class StixTextArrayComponent { @Input() public model: any; @Input() public propertyName: any; public addItemToArray(): void { if (!this.model.attributes[this.propertyName]) { this.model.attributes[this.propertyName] = []; } this.model.attributes[this.propertyName].unshift(''); } public removeItemFromArray(index: number): void { this.model.attributes[this.propertyName].splice(index, 1); } public
(index: number, obj: any): any { return index; } public makePlaceholder(prop: string) { let retVal = prop.replace(/e?s$/, ''); retVal = retVal.replace(/\b([a-z])(\w+)/g, (_, g1, g2) => { let word = g1.concat(g2); if (word === 'and' || word === 'or' || word === 'the') { return word; } return g1.toUpperCase() + g2; }); return retVal; } }
trackByIndex
identifier_name
stix-text-array.component.ts
import { Component, Input } from '@angular/core'; import { FormControl } from '@angular/forms'; @Component({ selector: 'stix-text-array', templateUrl: './stix-text-array.component.html' }) export class StixTextArrayComponent { @Input() public model: any; @Input() public propertyName: any; public addItemToArray(): void { if (!this.model.attributes[this.propertyName]) { this.model.attributes[this.propertyName] = []; } this.model.attributes[this.propertyName].unshift(''); } public removeItemFromArray(index: number): void { this.model.attributes[this.propertyName].splice(index, 1); } public trackByIndex(index: number, obj: any): any { return index; } public makePlaceholder(prop: string) { let retVal = prop.replace(/e?s$/, ''); retVal = retVal.replace(/\b([a-z])(\w+)/g, (_, g1, g2) => { let word = g1.concat(g2); if (word === 'and' || word === 'or' || word === 'the')
return g1.toUpperCase() + g2; }); return retVal; } }
{ return word; }
conditional_block
stix-text-array.component.ts
import { Component, Input } from '@angular/core'; import { FormControl } from '@angular/forms'; @Component({ selector: 'stix-text-array', templateUrl: './stix-text-array.component.html' }) export class StixTextArrayComponent { @Input() public model: any; @Input() public propertyName: any; public addItemToArray(): void { if (!this.model.attributes[this.propertyName]) { this.model.attributes[this.propertyName] = []; } this.model.attributes[this.propertyName].unshift(''); } public removeItemFromArray(index: number): void { this.model.attributes[this.propertyName].splice(index, 1); } public trackByIndex(index: number, obj: any): any { return index; } public makePlaceholder(prop: string)
}
{ let retVal = prop.replace(/e?s$/, ''); retVal = retVal.replace(/\b([a-z])(\w+)/g, (_, g1, g2) => { let word = g1.concat(g2); if (word === 'and' || word === 'or' || word === 'the') { return word; } return g1.toUpperCase() + g2; }); return retVal; }
identifier_body
stix-text-array.component.ts
import { Component, Input } from '@angular/core'; import { FormControl } from '@angular/forms'; @Component({ selector: 'stix-text-array', templateUrl: './stix-text-array.component.html' }) export class StixTextArrayComponent { @Input() public model: any; @Input() public propertyName: any; public addItemToArray(): void { if (!this.model.attributes[this.propertyName]) { this.model.attributes[this.propertyName] = []; } this.model.attributes[this.propertyName].unshift(''); } public removeItemFromArray(index: number): void { this.model.attributes[this.propertyName].splice(index, 1); } public trackByIndex(index: number, obj: any): any { return index; } public makePlaceholder(prop: string) { let retVal = prop.replace(/e?s$/, ''); retVal = retVal.replace(/\b([a-z])(\w+)/g, (_, g1, g2) => { let word = g1.concat(g2);
return retVal; } }
if (word === 'and' || word === 'or' || word === 'the') { return word; } return g1.toUpperCase() + g2; });
random_line_split
step4.py
# 14. print_log('\n14. Issuer (Trust Anchor) is creating a Credential Offer for Prover\n') cred_offer_json = await anoncreds.issuer_create_credential_offer(issuer_wallet_handle, cred_def_id) print_log('Credential Offer: ') pprint.pprint(json.loads(cred_offer_json)) # 15. print_log('\n15. Prover creates Credential Request for the given credential offer\n') (cred_req_json, cred_req_metadata_json) = \ await anoncreds.prover_create_credential_req(prover_wallet_handle, prover_did, cred_offer_json, cred_def_json, prover_link_secret_name) print_log('Credential Request: ') pprint.pprint(json.loads(cred_req_json)) # 16. print_log('\n16. Issuer (Trust Anchor) creates Credential for Credential Request\n') cred_values_json = json.dumps({ "sex": {"raw": "male", "encoded": "5944657099558967239210949258394887428692050081607692519917050011144233"}, "name": {"raw": "Alex", "encoded": "1139481716457488690172217916278103335"}, "height": {"raw": "175", "encoded": "175"}, "age": {"raw": "28", "encoded": "28"} }) (cred_json, _, _) = \ await anoncreds.issuer_create_credential(issuer_wallet_handle, cred_offer_json, cred_req_json, cred_values_json, None, None) print_log('Credential: ') pprint.pprint(json.loads(cred_json)) # 17. print_log('\n17. Prover processes and stores received Credential\n') await anoncreds.prover_store_credential(prover_wallet_handle, None, cred_req_metadata_json, cred_json, cred_def_json, None) # 18. print_log('\n18. Closing both wallet_handles and pool\n') await wallet.close_wallet(issuer_wallet_handle) await wallet.close_wallet(prover_wallet_handle) await pool.close_pool_ledger(pool_handle) # 19. print_log('\n19. Deleting created wallet_handles\n') await wallet.delete_wallet(issuer_wallet_config, issuer_wallet_credentials) await wallet.delete_wallet(prover_wallet_config, prover_wallet_credentials)
# 20. print_log('\n20. Deleting pool ledger config\n') await pool.delete_pool_ledger_config(pool_name)
random_line_split
totaleq.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use ast::{MetaItem, Item, Expr}; use codemap::Span; use ext::base::ExtCtxt; use ext::build::AstBuilder; use ext::deriving::generic::*; pub fn expand_deriving_totaleq(cx: &ExtCtxt, span: Span, mitem: @MetaItem, in_items: ~[@Item]) -> ~[@Item] { fn cs_equals(cx: &ExtCtxt, span: Span, substr: &Substructure) -> @Expr
let trait_def = TraitDef { cx: cx, span: span, path: Path::new(~["std", "cmp", "TotalEq"]), additional_bounds: ~[], generics: LifetimeBounds::empty(), methods: ~[ MethodDef { name: "equals", generics: LifetimeBounds::empty(), explicit_self: borrowed_explicit_self(), args: ~[borrowed_self()], ret_ty: Literal(Path::new(~["bool"])), inline: true, const_nonmatching: true, combine_substructure: cs_equals } ] }; trait_def.expand(mitem, in_items) }
{ cs_and(|cx, span, _, _| cx.expr_bool(span, false), cx, span, substr) }
identifier_body
totaleq.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use ast::{MetaItem, Item, Expr}; use codemap::Span; use ext::base::ExtCtxt; use ext::build::AstBuilder; use ext::deriving::generic::*; pub fn
(cx: &ExtCtxt, span: Span, mitem: @MetaItem, in_items: ~[@Item]) -> ~[@Item] { fn cs_equals(cx: &ExtCtxt, span: Span, substr: &Substructure) -> @Expr { cs_and(|cx, span, _, _| cx.expr_bool(span, false), cx, span, substr) } let trait_def = TraitDef { cx: cx, span: span, path: Path::new(~["std", "cmp", "TotalEq"]), additional_bounds: ~[], generics: LifetimeBounds::empty(), methods: ~[ MethodDef { name: "equals", generics: LifetimeBounds::empty(), explicit_self: borrowed_explicit_self(), args: ~[borrowed_self()], ret_ty: Literal(Path::new(~["bool"])), inline: true, const_nonmatching: true, combine_substructure: cs_equals } ] }; trait_def.expand(mitem, in_items) }
expand_deriving_totaleq
identifier_name
totaleq.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use ast::{MetaItem, Item, Expr}; use codemap::Span; use ext::base::ExtCtxt; use ext::build::AstBuilder; use ext::deriving::generic::*; pub fn expand_deriving_totaleq(cx: &ExtCtxt, span: Span, mitem: @MetaItem, in_items: ~[@Item]) -> ~[@Item] { fn cs_equals(cx: &ExtCtxt, span: Span, substr: &Substructure) -> @Expr { cs_and(|cx, span, _, _| cx.expr_bool(span, false), cx, span, substr) } let trait_def = TraitDef { cx: cx, span: span, path: Path::new(~["std", "cmp", "TotalEq"]), additional_bounds: ~[], generics: LifetimeBounds::empty(), methods: ~[ MethodDef { name: "equals", generics: LifetimeBounds::empty(), explicit_self: borrowed_explicit_self(), args: ~[borrowed_self()], ret_ty: Literal(Path::new(~["bool"])), inline: true, const_nonmatching: true, combine_substructure: cs_equals
} ] }; trait_def.expand(mitem, in_items) }
random_line_split
ramsAndSheeps.js
$(document).ready(function () { $('#userData').hide(); $('#topScores').show(); // enchanced method addEventListener function addEventListener(selector, eventType, listener) { $(selector).on(eventType, listener); } function trigerClick($button) { $button.click(); } var GameManager = (function () { var numberToGuess = []; var guessNumber = []; var guesses = 0; function getRandomNumber() { var newNumber = []; guesses = 0; newNumber[0] = Math.round(Math.random() * 8 + 1); // first digit must be bigger than 0 newNumber[1] = Math.round(Math.random() * 9); newNumber[2] = Math.round(Math.random() * 9); newNumber[3] = Math.round(Math.random() * 9); numberToGuess = newNumber; } function getUserInput(value) { value = validateNumber(value); guessNumber = String(parseInt(value)).split(''); } function validateNumber(number) { number = number.trim(); if (number.length != 4) { throw new Error("The number must be 4 digits long!"); } number = String(parseInt(number)); if (isNaN(number) || (number < 1000 || number > 10000)) { throw new Error("This is not a 4 digit number!"); } return number; } function checkNumber() { var rams = 0; var sheeps = 0; guesses += 1; //numberToGuess = [6, 1, 5, 4]; //guessNumber = [2, 3, 4, 5]; //numberToGuess = [5, 5, 8, 8]; //guessNumber = [8, 8, 8, 5]; var counted = [false, false, false, false]; //console.log(numberToGuess); //console.log(guessNumber); for (var i = 0; i < numberToGuess.length; i++) { if (guessNumber[i] == numberToGuess[i]) { //console.log(i + ' - ' + guessNumber[i] + ' ' + numberToGuess[i] + ' <- ram'); rams++; if (counted[i]) { sheeps--; } counted[i] = true; } else { for (var j = 0; j < numberToGuess.length; j++) { if (!counted[j] && guessNumber[i] == numberToGuess[j]) { //console.log(i + ' ' + j + ' - ' + guessNumber[i] + ' ' + numberToGuess[j] + ' <- sheep'); sheeps++; counted[j] = true; break; } } } } manageResult(guessNumber, rams, sheeps); } function manageResult(guessNumber, rams, sheeps) { var ul = $('#guesses ul'); var li = $('<li>'); if (rams < 4) { li.text(guesses + ': (' + guessNumber.join('') + ') You have ' + rams + ' rams and ' + sheeps + ' sheeps!'); ul.prepend(li); } else { $('#guesses').hide(); $('#userData').fadeIn(); } } function getUserName(name) { //validations return name; } function getUserGuesses() { return guesses; } return { getRandomNumber: getRandomNumber, getUserInput: getUserInput, getUserName: getUserName, getUserGuesses: getUserGuesses,
var ramsAndSheepsHighScores = JSON.parse(localStorage.getItem('ramsAndSheepsHighScores')) || []; function addScore(name, guesses) { var user = { name: name, score: guesses } ramsAndSheepsHighScores.push(user); var sortedHighScores = _.chain(ramsAndSheepsHighScores) .sortBy(function (user) { return user.name; }) .sortBy(function (user) { return user.score; }) .first(5).value(); console.log(sortedHighScores); localStorage.setItem('ramsAndSheepsHighScores', JSON.stringify(sortedHighScores)); } function showAll() { var allScores = JSON.parse(localStorage.getItem('ramsAndSheepsHighScores')) || []; var ol = $('#topScores ol'); ol.empty(); _.chain(ramsAndSheepsHighScores) .each(function (user) { var li = $('<li>'); li.text(user.name + ' ' + user.score); ol.append(li); }); } return { addScore: addScore, showAll: showAll } })(); // hack the input for non digits $("#userInput").on({ // When a new character was typed in keydown: function (e) { var key = e.which; // the enter key code if (key == 13) { trigerClick($('#guessBtn')); return false; } // if something else than [0-9] or BackSpace (BS == 8) is pressed, cancel the input if (((key < 48 || key > 57) && (key < 96 || key > 105)) && key !== 8) { return false; } }, // When non digits managed to "sneak in" via copy/paste change: function () { // Regex-remove all non digits in the final value this.value = this.value.replace(/\D/g, "") } }); addEventListener('#guessBtn', 'click', function (event) { var $userInput = $('#userInput'); GameManager.getUserInput($userInput[0].value); GameManager.checkNumber(); }); addEventListener('#getNameBtn', 'click', function (event) { var $userName = $('#userName'); var userName = GameManager.getUserName($userName[0].value); HighScores.addScore(userName, GameManager.getUserGuesses()); $('#userData').hide(); HighScores.showAll(); $('#topScores').fadeIn(); }); addEventListener('#resetBtn', 'click', function (event) { var userInput = $('#userInput'); var guessesUl = $('#guesses ul'); guessesUl.empty(); userInput[0].value = ""; GameManager.getRandomNumber(); }); // add the scores HighScores.showAll(); // start the game GameManager.getRandomNumber(); });
checkNumber: checkNumber } })(); var HighScores = (function () {
random_line_split
ramsAndSheeps.js
$(document).ready(function () { $('#userData').hide(); $('#topScores').show(); // enchanced method addEventListener function addEventListener(selector, eventType, listener) { $(selector).on(eventType, listener); } function trigerClick($button) { $button.click(); } var GameManager = (function () { var numberToGuess = []; var guessNumber = []; var guesses = 0; function getRandomNumber() { var newNumber = []; guesses = 0; newNumber[0] = Math.round(Math.random() * 8 + 1); // first digit must be bigger than 0 newNumber[1] = Math.round(Math.random() * 9); newNumber[2] = Math.round(Math.random() * 9); newNumber[3] = Math.round(Math.random() * 9); numberToGuess = newNumber; } function getUserInput(value) { value = validateNumber(value); guessNumber = String(parseInt(value)).split(''); } function validateNumber(number) { number = number.trim(); if (number.length != 4) { throw new Error("The number must be 4 digits long!"); } number = String(parseInt(number)); if (isNaN(number) || (number < 1000 || number > 10000)) { throw new Error("This is not a 4 digit number!"); } return number; } function checkNumber() { var rams = 0; var sheeps = 0; guesses += 1; //numberToGuess = [6, 1, 5, 4]; //guessNumber = [2, 3, 4, 5]; //numberToGuess = [5, 5, 8, 8]; //guessNumber = [8, 8, 8, 5]; var counted = [false, false, false, false]; //console.log(numberToGuess); //console.log(guessNumber); for (var i = 0; i < numberToGuess.length; i++) { if (guessNumber[i] == numberToGuess[i]) { //console.log(i + ' - ' + guessNumber[i] + ' ' + numberToGuess[i] + ' <- ram'); rams++; if (counted[i]) { sheeps--; } counted[i] = true; } else { for (var j = 0; j < numberToGuess.length; j++) { if (!counted[j] && guessNumber[i] == numberToGuess[j]) { //console.log(i + ' ' + j + ' - ' + guessNumber[i] + ' ' + numberToGuess[j] + ' <- sheep'); sheeps++; counted[j] = true; break; } } } } manageResult(guessNumber, rams, sheeps); } function ma
uessNumber, rams, sheeps) { var ul = $('#guesses ul'); var li = $('<li>'); if (rams < 4) { li.text(guesses + ': (' + guessNumber.join('') + ') You have ' + rams + ' rams and ' + sheeps + ' sheeps!'); ul.prepend(li); } else { $('#guesses').hide(); $('#userData').fadeIn(); } } function getUserName(name) { //validations return name; } function getUserGuesses() { return guesses; } return { getRandomNumber: getRandomNumber, getUserInput: getUserInput, getUserName: getUserName, getUserGuesses: getUserGuesses, checkNumber: checkNumber } })(); var HighScores = (function () { var ramsAndSheepsHighScores = JSON.parse(localStorage.getItem('ramsAndSheepsHighScores')) || []; function addScore(name, guesses) { var user = { name: name, score: guesses } ramsAndSheepsHighScores.push(user); var sortedHighScores = _.chain(ramsAndSheepsHighScores) .sortBy(function (user) { return user.name; }) .sortBy(function (user) { return user.score; }) .first(5).value(); console.log(sortedHighScores); localStorage.setItem('ramsAndSheepsHighScores', JSON.stringify(sortedHighScores)); } function showAll() { var allScores = JSON.parse(localStorage.getItem('ramsAndSheepsHighScores')) || []; var ol = $('#topScores ol'); ol.empty(); _.chain(ramsAndSheepsHighScores) .each(function (user) { var li = $('<li>'); li.text(user.name + ' ' + user.score); ol.append(li); }); } return { addScore: addScore, showAll: showAll } })(); // hack the input for non digits $("#userInput").on({ // When a new character was typed in keydown: function (e) { var key = e.which; // the enter key code if (key == 13) { trigerClick($('#guessBtn')); return false; } // if something else than [0-9] or BackSpace (BS == 8) is pressed, cancel the input if (((key < 48 || key > 57) && (key < 96 || key > 105)) && key !== 8) { return false; } }, // When non digits managed to "sneak in" via copy/paste change: function () { // Regex-remove all non digits in the final value this.value = this.value.replace(/\D/g, "") } }); addEventListener('#guessBtn', 'click', function (event) { var $userInput = $('#userInput'); GameManager.getUserInput($userInput[0].value); GameManager.checkNumber(); }); addEventListener('#getNameBtn', 'click', function (event) { var $userName = $('#userName'); var userName = GameManager.getUserName($userName[0].value); HighScores.addScore(userName, GameManager.getUserGuesses()); $('#userData').hide(); HighScores.showAll(); $('#topScores').fadeIn(); }); addEventListener('#resetBtn', 'click', function (event) { var userInput = $('#userInput'); var guessesUl = $('#guesses ul'); guessesUl.empty(); userInput[0].value = ""; GameManager.getRandomNumber(); }); // add the scores HighScores.showAll(); // start the game GameManager.getRandomNumber(); });
nageResult(g
identifier_name
ramsAndSheeps.js
$(document).ready(function () { $('#userData').hide(); $('#topScores').show(); // enchanced method addEventListener function addEventListener(selector, eventType, listener) { $(selector).on(eventType, listener); } function trigerClick($button) { $button.click(); } var GameManager = (function () { var numberToGuess = []; var guessNumber = []; var guesses = 0; function getRandomNumber() {
function getUserInput(value) { value = validateNumber(value); guessNumber = String(parseInt(value)).split(''); } function validateNumber(number) { number = number.trim(); if (number.length != 4) { throw new Error("The number must be 4 digits long!"); } number = String(parseInt(number)); if (isNaN(number) || (number < 1000 || number > 10000)) { throw new Error("This is not a 4 digit number!"); } return number; } function checkNumber() { var rams = 0; var sheeps = 0; guesses += 1; //numberToGuess = [6, 1, 5, 4]; //guessNumber = [2, 3, 4, 5]; //numberToGuess = [5, 5, 8, 8]; //guessNumber = [8, 8, 8, 5]; var counted = [false, false, false, false]; //console.log(numberToGuess); //console.log(guessNumber); for (var i = 0; i < numberToGuess.length; i++) { if (guessNumber[i] == numberToGuess[i]) { //console.log(i + ' - ' + guessNumber[i] + ' ' + numberToGuess[i] + ' <- ram'); rams++; if (counted[i]) { sheeps--; } counted[i] = true; } else { for (var j = 0; j < numberToGuess.length; j++) { if (!counted[j] && guessNumber[i] == numberToGuess[j]) { //console.log(i + ' ' + j + ' - ' + guessNumber[i] + ' ' + numberToGuess[j] + ' <- sheep'); sheeps++; counted[j] = true; break; } } } } manageResult(guessNumber, rams, sheeps); } function manageResult(guessNumber, rams, sheeps) { var ul = $('#guesses ul'); var li = $('<li>'); if (rams < 4) { li.text(guesses + ': (' + guessNumber.join('') + ') You have ' + rams + ' rams and ' + sheeps + ' sheeps!'); ul.prepend(li); } else { $('#guesses').hide(); $('#userData').fadeIn(); } } function getUserName(name) { //validations return name; } function getUserGuesses() { return guesses; } return { getRandomNumber: getRandomNumber, getUserInput: getUserInput, getUserName: getUserName, getUserGuesses: getUserGuesses, checkNumber: checkNumber } })(); var HighScores = (function () { var ramsAndSheepsHighScores = JSON.parse(localStorage.getItem('ramsAndSheepsHighScores')) || []; function addScore(name, guesses) { var user = { name: name, score: guesses } ramsAndSheepsHighScores.push(user); var sortedHighScores = _.chain(ramsAndSheepsHighScores) .sortBy(function (user) { return user.name; }) .sortBy(function (user) { return user.score; }) .first(5).value(); console.log(sortedHighScores); localStorage.setItem('ramsAndSheepsHighScores', JSON.stringify(sortedHighScores)); } function showAll() { var allScores = JSON.parse(localStorage.getItem('ramsAndSheepsHighScores')) || []; var ol = $('#topScores ol'); ol.empty(); _.chain(ramsAndSheepsHighScores) .each(function (user) { var li = $('<li>'); li.text(user.name + ' ' + user.score); ol.append(li); }); } return { addScore: addScore, showAll: showAll } })(); // hack the input for non digits $("#userInput").on({ // When a new character was typed in keydown: function (e) { var key = e.which; // the enter key code if (key == 13) { trigerClick($('#guessBtn')); return false; } // if something else than [0-9] or BackSpace (BS == 8) is pressed, cancel the input if (((key < 48 || key > 57) && (key < 96 || key > 105)) && key !== 8) { return false; } }, // When non digits managed to "sneak in" via copy/paste change: function () { // Regex-remove all non digits in the final value this.value = this.value.replace(/\D/g, "") } }); addEventListener('#guessBtn', 'click', function (event) { var $userInput = $('#userInput'); GameManager.getUserInput($userInput[0].value); GameManager.checkNumber(); }); addEventListener('#getNameBtn', 'click', function (event) { var $userName = $('#userName'); var userName = GameManager.getUserName($userName[0].value); HighScores.addScore(userName, GameManager.getUserGuesses()); $('#userData').hide(); HighScores.showAll(); $('#topScores').fadeIn(); }); addEventListener('#resetBtn', 'click', function (event) { var userInput = $('#userInput'); var guessesUl = $('#guesses ul'); guessesUl.empty(); userInput[0].value = ""; GameManager.getRandomNumber(); }); // add the scores HighScores.showAll(); // start the game GameManager.getRandomNumber(); });
var newNumber = []; guesses = 0; newNumber[0] = Math.round(Math.random() * 8 + 1); // first digit must be bigger than 0 newNumber[1] = Math.round(Math.random() * 9); newNumber[2] = Math.round(Math.random() * 9); newNumber[3] = Math.round(Math.random() * 9); numberToGuess = newNumber; }
identifier_body
ramsAndSheeps.js
$(document).ready(function () { $('#userData').hide(); $('#topScores').show(); // enchanced method addEventListener function addEventListener(selector, eventType, listener) { $(selector).on(eventType, listener); } function trigerClick($button) { $button.click(); } var GameManager = (function () { var numberToGuess = []; var guessNumber = []; var guesses = 0; function getRandomNumber() { var newNumber = []; guesses = 0; newNumber[0] = Math.round(Math.random() * 8 + 1); // first digit must be bigger than 0 newNumber[1] = Math.round(Math.random() * 9); newNumber[2] = Math.round(Math.random() * 9); newNumber[3] = Math.round(Math.random() * 9); numberToGuess = newNumber; } function getUserInput(value) { value = validateNumber(value); guessNumber = String(parseInt(value)).split(''); } function validateNumber(number) { number = number.trim(); if (number.length != 4) {
number = String(parseInt(number)); if (isNaN(number) || (number < 1000 || number > 10000)) { throw new Error("This is not a 4 digit number!"); } return number; } function checkNumber() { var rams = 0; var sheeps = 0; guesses += 1; //numberToGuess = [6, 1, 5, 4]; //guessNumber = [2, 3, 4, 5]; //numberToGuess = [5, 5, 8, 8]; //guessNumber = [8, 8, 8, 5]; var counted = [false, false, false, false]; //console.log(numberToGuess); //console.log(guessNumber); for (var i = 0; i < numberToGuess.length; i++) { if (guessNumber[i] == numberToGuess[i]) { //console.log(i + ' - ' + guessNumber[i] + ' ' + numberToGuess[i] + ' <- ram'); rams++; if (counted[i]) { sheeps--; } counted[i] = true; } else { for (var j = 0; j < numberToGuess.length; j++) { if (!counted[j] && guessNumber[i] == numberToGuess[j]) { //console.log(i + ' ' + j + ' - ' + guessNumber[i] + ' ' + numberToGuess[j] + ' <- sheep'); sheeps++; counted[j] = true; break; } } } } manageResult(guessNumber, rams, sheeps); } function manageResult(guessNumber, rams, sheeps) { var ul = $('#guesses ul'); var li = $('<li>'); if (rams < 4) { li.text(guesses + ': (' + guessNumber.join('') + ') You have ' + rams + ' rams and ' + sheeps + ' sheeps!'); ul.prepend(li); } else { $('#guesses').hide(); $('#userData').fadeIn(); } } function getUserName(name) { //validations return name; } function getUserGuesses() { return guesses; } return { getRandomNumber: getRandomNumber, getUserInput: getUserInput, getUserName: getUserName, getUserGuesses: getUserGuesses, checkNumber: checkNumber } })(); var HighScores = (function () { var ramsAndSheepsHighScores = JSON.parse(localStorage.getItem('ramsAndSheepsHighScores')) || []; function addScore(name, guesses) { var user = { name: name, score: guesses } ramsAndSheepsHighScores.push(user); var sortedHighScores = _.chain(ramsAndSheepsHighScores) .sortBy(function (user) { return user.name; }) .sortBy(function (user) { return user.score; }) .first(5).value(); console.log(sortedHighScores); localStorage.setItem('ramsAndSheepsHighScores', JSON.stringify(sortedHighScores)); } function showAll() { var allScores = JSON.parse(localStorage.getItem('ramsAndSheepsHighScores')) || []; var ol = $('#topScores ol'); ol.empty(); _.chain(ramsAndSheepsHighScores) .each(function (user) { var li = $('<li>'); li.text(user.name + ' ' + user.score); ol.append(li); }); } return { addScore: addScore, showAll: showAll } })(); // hack the input for non digits $("#userInput").on({ // When a new character was typed in keydown: function (e) { var key = e.which; // the enter key code if (key == 13) { trigerClick($('#guessBtn')); return false; } // if something else than [0-9] or BackSpace (BS == 8) is pressed, cancel the input if (((key < 48 || key > 57) && (key < 96 || key > 105)) && key !== 8) { return false; } }, // When non digits managed to "sneak in" via copy/paste change: function () { // Regex-remove all non digits in the final value this.value = this.value.replace(/\D/g, "") } }); addEventListener('#guessBtn', 'click', function (event) { var $userInput = $('#userInput'); GameManager.getUserInput($userInput[0].value); GameManager.checkNumber(); }); addEventListener('#getNameBtn', 'click', function (event) { var $userName = $('#userName'); var userName = GameManager.getUserName($userName[0].value); HighScores.addScore(userName, GameManager.getUserGuesses()); $('#userData').hide(); HighScores.showAll(); $('#topScores').fadeIn(); }); addEventListener('#resetBtn', 'click', function (event) { var userInput = $('#userInput'); var guessesUl = $('#guesses ul'); guessesUl.empty(); userInput[0].value = ""; GameManager.getRandomNumber(); }); // add the scores HighScores.showAll(); // start the game GameManager.getRandomNumber(); });
throw new Error("The number must be 4 digits long!"); }
conditional_block
unittest_utils.py
# Copyright 2017 The TensorFlow Authors 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. # ============================================================================== """Functions to make unit testing easier.""" import StringIO import numpy as np from PIL import Image as PILImage import tensorflow as tf def create_random_image(image_format, shape): """Creates an image with random values. Args: image_format: An image format (PNG or JPEG). shape: A tuple with image shape (including channels). Returns: A tuple (<numpy ndarray>, <a string with encoded image>) """ image = np.random.randint(low=0, high=255, size=shape, dtype='uint8') io = StringIO.StringIO() image_pil = PILImage.fromarray(image) image_pil.save(io, image_format, subsampling=0, quality=100) return image, io.getvalue() def create_serialized_example(name_to_values): """Creates a tf.Example proto using a dictionary. It automatically detects type of values and define a corresponding feature. Args: name_to_values: A dictionary. Returns: tf.Example proto. """ example = tf.train.Example() for name, values in name_to_values.items(): feature = example.features.feature[name] if isinstance(values[0], str): add = feature.bytes_list.value.extend elif isinstance(values[0], float): add = feature.float32_list.value.extend elif isinstance(values[0], int):
else: raise AssertionError('Unsupported type: %s' % type(values[0])) add(values) return example.SerializeToString()
add = feature.int64_list.value.extend
conditional_block
unittest_utils.py
# Copyright 2017 The TensorFlow Authors 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. # ============================================================================== """Functions to make unit testing easier.""" import StringIO import numpy as np from PIL import Image as PILImage import tensorflow as tf def create_random_image(image_format, shape):
def create_serialized_example(name_to_values): """Creates a tf.Example proto using a dictionary. It automatically detects type of values and define a corresponding feature. Args: name_to_values: A dictionary. Returns: tf.Example proto. """ example = tf.train.Example() for name, values in name_to_values.items(): feature = example.features.feature[name] if isinstance(values[0], str): add = feature.bytes_list.value.extend elif isinstance(values[0], float): add = feature.float32_list.value.extend elif isinstance(values[0], int): add = feature.int64_list.value.extend else: raise AssertionError('Unsupported type: %s' % type(values[0])) add(values) return example.SerializeToString()
"""Creates an image with random values. Args: image_format: An image format (PNG or JPEG). shape: A tuple with image shape (including channels). Returns: A tuple (<numpy ndarray>, <a string with encoded image>) """ image = np.random.randint(low=0, high=255, size=shape, dtype='uint8') io = StringIO.StringIO() image_pil = PILImage.fromarray(image) image_pil.save(io, image_format, subsampling=0, quality=100) return image, io.getvalue()
identifier_body
unittest_utils.py
# Copyright 2017 The TensorFlow Authors 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. # ============================================================================== """Functions to make unit testing easier.""" import StringIO import numpy as np from PIL import Image as PILImage import tensorflow as tf def create_random_image(image_format, shape): """Creates an image with random values. Args: image_format: An image format (PNG or JPEG). shape: A tuple with image shape (including channels). Returns: A tuple (<numpy ndarray>, <a string with encoded image>) """ image = np.random.randint(low=0, high=255, size=shape, dtype='uint8') io = StringIO.StringIO() image_pil = PILImage.fromarray(image) image_pil.save(io, image_format, subsampling=0, quality=100) return image, io.getvalue() def create_serialized_example(name_to_values): """Creates a tf.Example proto using a dictionary. It automatically detects type of values and define a corresponding feature. Args:
Returns: tf.Example proto. """ example = tf.train.Example() for name, values in name_to_values.items(): feature = example.features.feature[name] if isinstance(values[0], str): add = feature.bytes_list.value.extend elif isinstance(values[0], float): add = feature.float32_list.value.extend elif isinstance(values[0], int): add = feature.int64_list.value.extend else: raise AssertionError('Unsupported type: %s' % type(values[0])) add(values) return example.SerializeToString()
name_to_values: A dictionary.
random_line_split
unittest_utils.py
# Copyright 2017 The TensorFlow Authors 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. # ============================================================================== """Functions to make unit testing easier.""" import StringIO import numpy as np from PIL import Image as PILImage import tensorflow as tf def
(image_format, shape): """Creates an image with random values. Args: image_format: An image format (PNG or JPEG). shape: A tuple with image shape (including channels). Returns: A tuple (<numpy ndarray>, <a string with encoded image>) """ image = np.random.randint(low=0, high=255, size=shape, dtype='uint8') io = StringIO.StringIO() image_pil = PILImage.fromarray(image) image_pil.save(io, image_format, subsampling=0, quality=100) return image, io.getvalue() def create_serialized_example(name_to_values): """Creates a tf.Example proto using a dictionary. It automatically detects type of values and define a corresponding feature. Args: name_to_values: A dictionary. Returns: tf.Example proto. """ example = tf.train.Example() for name, values in name_to_values.items(): feature = example.features.feature[name] if isinstance(values[0], str): add = feature.bytes_list.value.extend elif isinstance(values[0], float): add = feature.float32_list.value.extend elif isinstance(values[0], int): add = feature.int64_list.value.extend else: raise AssertionError('Unsupported type: %s' % type(values[0])) add(values) return example.SerializeToString()
create_random_image
identifier_name
migration-0003.ts
import {DesktopCryptoFacade} from "../../DesktopCryptoFacade" import type {Config} from "../ConfigCommon" import {downcast} from "@tutao/tutanota-utils" import type {DesktopKeyStoreFacade} from "../../KeyStoreFacadeImpl" import {log} from "../../DesktopLog" async function
(oldConfig: Config, crypto: DesktopCryptoFacade, keyStoreFacade: DesktopKeyStoreFacade): Promise<void> { Object.assign(oldConfig, { desktopConfigVersion: 3, }) if (oldConfig.pushIdentifier) { try { const deviceKey = await keyStoreFacade.getDeviceKey() Object.assign(oldConfig, { sseInfo: crypto.aesEncryptObject(deviceKey, downcast(oldConfig.pushIdentifier)), }) } catch (e) { // cannot read device key, just remove sseInfo from old config log.warn("migration003: could not read device key, will not save sseInfo", e) } delete oldConfig.pushIdentifier } } export const migrateClient = migrate export const migrateAdmin = migrate
migrate
identifier_name
migration-0003.ts
import {DesktopCryptoFacade} from "../../DesktopCryptoFacade" import type {Config} from "../ConfigCommon" import {downcast} from "@tutao/tutanota-utils" import type {DesktopKeyStoreFacade} from "../../KeyStoreFacadeImpl" import {log} from "../../DesktopLog" async function migrate(oldConfig: Config, crypto: DesktopCryptoFacade, keyStoreFacade: DesktopKeyStoreFacade): Promise<void> { Object.assign(oldConfig, { desktopConfigVersion: 3, }) if (oldConfig.pushIdentifier)
} export const migrateClient = migrate export const migrateAdmin = migrate
{ try { const deviceKey = await keyStoreFacade.getDeviceKey() Object.assign(oldConfig, { sseInfo: crypto.aesEncryptObject(deviceKey, downcast(oldConfig.pushIdentifier)), }) } catch (e) { // cannot read device key, just remove sseInfo from old config log.warn("migration003: could not read device key, will not save sseInfo", e) } delete oldConfig.pushIdentifier }
conditional_block
migration-0003.ts
import {DesktopCryptoFacade} from "../../DesktopCryptoFacade" import type {Config} from "../ConfigCommon" import {downcast} from "@tutao/tutanota-utils" import type {DesktopKeyStoreFacade} from "../../KeyStoreFacadeImpl" import {log} from "../../DesktopLog" async function migrate(oldConfig: Config, crypto: DesktopCryptoFacade, keyStoreFacade: DesktopKeyStoreFacade): Promise<void>
export const migrateClient = migrate export const migrateAdmin = migrate
{ Object.assign(oldConfig, { desktopConfigVersion: 3, }) if (oldConfig.pushIdentifier) { try { const deviceKey = await keyStoreFacade.getDeviceKey() Object.assign(oldConfig, { sseInfo: crypto.aesEncryptObject(deviceKey, downcast(oldConfig.pushIdentifier)), }) } catch (e) { // cannot read device key, just remove sseInfo from old config log.warn("migration003: could not read device key, will not save sseInfo", e) } delete oldConfig.pushIdentifier } }
identifier_body
migration-0003.ts
import {DesktopCryptoFacade} from "../../DesktopCryptoFacade" import type {Config} from "../ConfigCommon" import {downcast} from "@tutao/tutanota-utils" import type {DesktopKeyStoreFacade} from "../../KeyStoreFacadeImpl" import {log} from "../../DesktopLog" async function migrate(oldConfig: Config, crypto: DesktopCryptoFacade, keyStoreFacade: DesktopKeyStoreFacade): Promise<void> { Object.assign(oldConfig, { desktopConfigVersion: 3,
}) if (oldConfig.pushIdentifier) { try { const deviceKey = await keyStoreFacade.getDeviceKey() Object.assign(oldConfig, { sseInfo: crypto.aesEncryptObject(deviceKey, downcast(oldConfig.pushIdentifier)), }) } catch (e) { // cannot read device key, just remove sseInfo from old config log.warn("migration003: could not read device key, will not save sseInfo", e) } delete oldConfig.pushIdentifier } } export const migrateClient = migrate export const migrateAdmin = migrate
random_line_split
__init__.py
""" support for presenting detailed information in failing assertions. """ import py import sys import pytest from _pytest.monkeypatch import monkeypatch from _pytest.assertion import util def pytest_addoption(parser): group = parser.getgroup("debugconfig") group.addoption('--assert', action="store", dest="assertmode", choices=("rewrite", "reinterp", "plain",), default="rewrite", metavar="MODE", help="""control assertion debugging tools. 'plain' performs no assertion debugging. 'reinterp' reinterprets assert statements after they failed to provide assertion expression information. 'rewrite' (the default) rewrites assert statements in test modules on import to provide assert expression information. """) group.addoption('--no-assert', action="store_true", default=False, dest="noassert", help="DEPRECATED equivalent to --assert=plain") group.addoption('--nomagic', action="store_true", default=False, dest="nomagic", help="DEPRECATED equivalent to --assert=plain") class AssertionState: """State for the assertion plugin.""" def
(self, config, mode): self.mode = mode self.trace = config.trace.root.get("assertion") def pytest_configure(config): mode = config.getvalue("assertmode") if config.getvalue("noassert") or config.getvalue("nomagic"): mode = "plain" if mode == "rewrite": try: import ast except ImportError: mode = "reinterp" else: if sys.platform.startswith('java'): mode = "reinterp" if mode != "plain": _load_modules(mode) m = monkeypatch() config._cleanup.append(m.undo) m.setattr(py.builtin.builtins, 'AssertionError', reinterpret.AssertionError) hook = None if mode == "rewrite": hook = rewrite.AssertionRewritingHook() sys.meta_path.append(hook) warn_about_missing_assertion(mode) config._assertstate = AssertionState(config, mode) config._assertstate.hook = hook config._assertstate.trace("configured with mode set to %r" % (mode,)) def pytest_unconfigure(config): hook = config._assertstate.hook if hook is not None: sys.meta_path.remove(hook) def pytest_collection(session): # this hook is only called when test modules are collected # so for example not in the master process of pytest-xdist # (which does not collect test modules) hook = session.config._assertstate.hook if hook is not None: hook.set_session(session) def pytest_runtest_setup(item): def callbinrepr(op, left, right): hook_result = item.ihook.pytest_assertrepr_compare( config=item.config, op=op, left=left, right=right) for new_expl in hook_result: if new_expl: res = '\n~'.join(new_expl) if item.config.getvalue("assertmode") == "rewrite": # The result will be fed back a python % formatting # operation, which will fail if there are extraneous # '%'s in the string. Escape them here. res = res.replace("%", "%%") return res util._reprcompare = callbinrepr def pytest_runtest_teardown(item): util._reprcompare = None def pytest_sessionfinish(session): hook = session.config._assertstate.hook if hook is not None: hook.session = None def _load_modules(mode): """Lazily import assertion related code.""" global rewrite, reinterpret from _pytest.assertion import reinterpret if mode == "rewrite": from _pytest.assertion import rewrite def warn_about_missing_assertion(mode): try: assert False except AssertionError: pass else: if mode == "rewrite": specifically = ("assertions which are not in test modules " "will be ignored") else: specifically = "failing tests may report as passing" sys.stderr.write("WARNING: " + specifically + " because assert statements are not executed " "by the underlying Python interpreter " "(are you using python -O?)\n") pytest_assertrepr_compare = util.assertrepr_compare
__init__
identifier_name
__init__.py
""" support for presenting detailed information in failing assertions. """ import py import sys import pytest from _pytest.monkeypatch import monkeypatch from _pytest.assertion import util def pytest_addoption(parser): group = parser.getgroup("debugconfig") group.addoption('--assert', action="store", dest="assertmode", choices=("rewrite", "reinterp", "plain",), default="rewrite", metavar="MODE", help="""control assertion debugging tools. 'plain' performs no assertion debugging. 'reinterp' reinterprets assert statements after they failed to provide assertion expression information. 'rewrite' (the default) rewrites assert statements in test modules on import to provide assert expression information. """) group.addoption('--no-assert', action="store_true", default=False, dest="noassert", help="DEPRECATED equivalent to --assert=plain") group.addoption('--nomagic', action="store_true", default=False, dest="nomagic", help="DEPRECATED equivalent to --assert=plain") class AssertionState: """State for the assertion plugin.""" def __init__(self, config, mode): self.mode = mode self.trace = config.trace.root.get("assertion") def pytest_configure(config): mode = config.getvalue("assertmode") if config.getvalue("noassert") or config.getvalue("nomagic"): mode = "plain" if mode == "rewrite": try: import ast except ImportError: mode = "reinterp" else: if sys.platform.startswith('java'): mode = "reinterp" if mode != "plain": _load_modules(mode) m = monkeypatch() config._cleanup.append(m.undo) m.setattr(py.builtin.builtins, 'AssertionError', reinterpret.AssertionError) hook = None if mode == "rewrite": hook = rewrite.AssertionRewritingHook() sys.meta_path.append(hook) warn_about_missing_assertion(mode) config._assertstate = AssertionState(config, mode) config._assertstate.hook = hook config._assertstate.trace("configured with mode set to %r" % (mode,)) def pytest_unconfigure(config): hook = config._assertstate.hook if hook is not None: sys.meta_path.remove(hook) def pytest_collection(session): # this hook is only called when test modules are collected # so for example not in the master process of pytest-xdist # (which does not collect test modules) hook = session.config._assertstate.hook if hook is not None: hook.set_session(session) def pytest_runtest_setup(item): def callbinrepr(op, left, right): hook_result = item.ihook.pytest_assertrepr_compare( config=item.config, op=op, left=left, right=right) for new_expl in hook_result: if new_expl:
util._reprcompare = callbinrepr def pytest_runtest_teardown(item): util._reprcompare = None def pytest_sessionfinish(session): hook = session.config._assertstate.hook if hook is not None: hook.session = None def _load_modules(mode): """Lazily import assertion related code.""" global rewrite, reinterpret from _pytest.assertion import reinterpret if mode == "rewrite": from _pytest.assertion import rewrite def warn_about_missing_assertion(mode): try: assert False except AssertionError: pass else: if mode == "rewrite": specifically = ("assertions which are not in test modules " "will be ignored") else: specifically = "failing tests may report as passing" sys.stderr.write("WARNING: " + specifically + " because assert statements are not executed " "by the underlying Python interpreter " "(are you using python -O?)\n") pytest_assertrepr_compare = util.assertrepr_compare
res = '\n~'.join(new_expl) if item.config.getvalue("assertmode") == "rewrite": # The result will be fed back a python % formatting # operation, which will fail if there are extraneous # '%'s in the string. Escape them here. res = res.replace("%", "%%") return res
conditional_block
__init__.py
""" support for presenting detailed information in failing assertions. """ import py import sys import pytest from _pytest.monkeypatch import monkeypatch from _pytest.assertion import util def pytest_addoption(parser): group = parser.getgroup("debugconfig") group.addoption('--assert', action="store", dest="assertmode", choices=("rewrite", "reinterp", "plain",), default="rewrite", metavar="MODE", help="""control assertion debugging tools. 'plain' performs no assertion debugging. 'reinterp' reinterprets assert statements after they failed to provide assertion expression information. 'rewrite' (the default) rewrites assert statements in test modules on import to provide assert expression information. """) group.addoption('--no-assert', action="store_true", default=False, dest="noassert", help="DEPRECATED equivalent to --assert=plain") group.addoption('--nomagic', action="store_true", default=False, dest="nomagic", help="DEPRECATED equivalent to --assert=plain") class AssertionState: """State for the assertion plugin.""" def __init__(self, config, mode): self.mode = mode self.trace = config.trace.root.get("assertion") def pytest_configure(config): mode = config.getvalue("assertmode") if config.getvalue("noassert") or config.getvalue("nomagic"): mode = "plain" if mode == "rewrite": try: import ast except ImportError: mode = "reinterp" else: if sys.platform.startswith('java'): mode = "reinterp" if mode != "plain": _load_modules(mode) m = monkeypatch() config._cleanup.append(m.undo) m.setattr(py.builtin.builtins, 'AssertionError', reinterpret.AssertionError) hook = None if mode == "rewrite": hook = rewrite.AssertionRewritingHook() sys.meta_path.append(hook) warn_about_missing_assertion(mode) config._assertstate = AssertionState(config, mode) config._assertstate.hook = hook config._assertstate.trace("configured with mode set to %r" % (mode,)) def pytest_unconfigure(config): hook = config._assertstate.hook if hook is not None: sys.meta_path.remove(hook) def pytest_collection(session): # this hook is only called when test modules are collected # so for example not in the master process of pytest-xdist # (which does not collect test modules) hook = session.config._assertstate.hook if hook is not None: hook.set_session(session) def pytest_runtest_setup(item): def callbinrepr(op, left, right): hook_result = item.ihook.pytest_assertrepr_compare( config=item.config, op=op, left=left, right=right) for new_expl in hook_result: if new_expl: res = '\n~'.join(new_expl) if item.config.getvalue("assertmode") == "rewrite": # The result will be fed back a python % formatting # operation, which will fail if there are extraneous # '%'s in the string. Escape them here. res = res.replace("%", "%%") return res util._reprcompare = callbinrepr def pytest_runtest_teardown(item): util._reprcompare = None def pytest_sessionfinish(session):
def _load_modules(mode): """Lazily import assertion related code.""" global rewrite, reinterpret from _pytest.assertion import reinterpret if mode == "rewrite": from _pytest.assertion import rewrite def warn_about_missing_assertion(mode): try: assert False except AssertionError: pass else: if mode == "rewrite": specifically = ("assertions which are not in test modules " "will be ignored") else: specifically = "failing tests may report as passing" sys.stderr.write("WARNING: " + specifically + " because assert statements are not executed " "by the underlying Python interpreter " "(are you using python -O?)\n") pytest_assertrepr_compare = util.assertrepr_compare
hook = session.config._assertstate.hook if hook is not None: hook.session = None
identifier_body
__init__.py
""" support for presenting detailed information in failing assertions. """ import py import sys import pytest from _pytest.monkeypatch import monkeypatch from _pytest.assertion import util def pytest_addoption(parser): group = parser.getgroup("debugconfig") group.addoption('--assert', action="store", dest="assertmode", choices=("rewrite", "reinterp", "plain",),
help="""control assertion debugging tools. 'plain' performs no assertion debugging. 'reinterp' reinterprets assert statements after they failed to provide assertion expression information. 'rewrite' (the default) rewrites assert statements in test modules on import to provide assert expression information. """) group.addoption('--no-assert', action="store_true", default=False, dest="noassert", help="DEPRECATED equivalent to --assert=plain") group.addoption('--nomagic', action="store_true", default=False, dest="nomagic", help="DEPRECATED equivalent to --assert=plain") class AssertionState: """State for the assertion plugin.""" def __init__(self, config, mode): self.mode = mode self.trace = config.trace.root.get("assertion") def pytest_configure(config): mode = config.getvalue("assertmode") if config.getvalue("noassert") or config.getvalue("nomagic"): mode = "plain" if mode == "rewrite": try: import ast except ImportError: mode = "reinterp" else: if sys.platform.startswith('java'): mode = "reinterp" if mode != "plain": _load_modules(mode) m = monkeypatch() config._cleanup.append(m.undo) m.setattr(py.builtin.builtins, 'AssertionError', reinterpret.AssertionError) hook = None if mode == "rewrite": hook = rewrite.AssertionRewritingHook() sys.meta_path.append(hook) warn_about_missing_assertion(mode) config._assertstate = AssertionState(config, mode) config._assertstate.hook = hook config._assertstate.trace("configured with mode set to %r" % (mode,)) def pytest_unconfigure(config): hook = config._assertstate.hook if hook is not None: sys.meta_path.remove(hook) def pytest_collection(session): # this hook is only called when test modules are collected # so for example not in the master process of pytest-xdist # (which does not collect test modules) hook = session.config._assertstate.hook if hook is not None: hook.set_session(session) def pytest_runtest_setup(item): def callbinrepr(op, left, right): hook_result = item.ihook.pytest_assertrepr_compare( config=item.config, op=op, left=left, right=right) for new_expl in hook_result: if new_expl: res = '\n~'.join(new_expl) if item.config.getvalue("assertmode") == "rewrite": # The result will be fed back a python % formatting # operation, which will fail if there are extraneous # '%'s in the string. Escape them here. res = res.replace("%", "%%") return res util._reprcompare = callbinrepr def pytest_runtest_teardown(item): util._reprcompare = None def pytest_sessionfinish(session): hook = session.config._assertstate.hook if hook is not None: hook.session = None def _load_modules(mode): """Lazily import assertion related code.""" global rewrite, reinterpret from _pytest.assertion import reinterpret if mode == "rewrite": from _pytest.assertion import rewrite def warn_about_missing_assertion(mode): try: assert False except AssertionError: pass else: if mode == "rewrite": specifically = ("assertions which are not in test modules " "will be ignored") else: specifically = "failing tests may report as passing" sys.stderr.write("WARNING: " + specifically + " because assert statements are not executed " "by the underlying Python interpreter " "(are you using python -O?)\n") pytest_assertrepr_compare = util.assertrepr_compare
default="rewrite", metavar="MODE",
random_line_split
lxc-patch.py
# Yum plugin to re-patch container rootfs after a yum update is done # # Copyright (C) 2012 Oracle # # Authors: # Dwight Engen <dwight.engen@oracle.com> # # 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 Library General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # import os from fnmatch import fnmatch from yum.plugins import TYPE_INTERACTIVE from yum.plugins import PluginYumExit requires_api_version = '2.0' plugin_type = (TYPE_INTERACTIVE,) def posttrans_hook(conduit): pkgs = [] patch_required = False # If we aren't root, we can't have updated anything if os.geteuid(): return # See what packages have files that were patched confpkgs = conduit.confString('main', 'packages') if not confpkgs: return tmp = confpkgs.split(",") for confpkg in tmp: pkgs.append(confpkg.strip()) conduit.info(2, "lxc-patch: checking if updated pkgs need patching...") ts = conduit.getTsInfo() for tsmem in ts.getMembers(): for pkg in pkgs:
if patch_required: conduit.info(2, "lxc-patch: patching container...") os.spawnlp(os.P_WAIT, "lxc-patch", "lxc-patch", "--patch", "/")
if fnmatch(pkg, tsmem.po.name): patch_required = True
conditional_block
lxc-patch.py
# Yum plugin to re-patch container rootfs after a yum update is done # # Copyright (C) 2012 Oracle # # Authors: # Dwight Engen <dwight.engen@oracle.com> # # 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 Library General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # import os from fnmatch import fnmatch from yum.plugins import TYPE_INTERACTIVE from yum.plugins import PluginYumExit requires_api_version = '2.0' plugin_type = (TYPE_INTERACTIVE,) def posttrans_hook(conduit): pkgs = [] patch_required = False # If we aren't root, we can't have updated anything if os.geteuid(): return # See what packages have files that were patched confpkgs = conduit.confString('main', 'packages')
tmp = confpkgs.split(",") for confpkg in tmp: pkgs.append(confpkg.strip()) conduit.info(2, "lxc-patch: checking if updated pkgs need patching...") ts = conduit.getTsInfo() for tsmem in ts.getMembers(): for pkg in pkgs: if fnmatch(pkg, tsmem.po.name): patch_required = True if patch_required: conduit.info(2, "lxc-patch: patching container...") os.spawnlp(os.P_WAIT, "lxc-patch", "lxc-patch", "--patch", "/")
if not confpkgs: return
random_line_split
lxc-patch.py
# Yum plugin to re-patch container rootfs after a yum update is done # # Copyright (C) 2012 Oracle # # Authors: # Dwight Engen <dwight.engen@oracle.com> # # 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 Library General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # import os from fnmatch import fnmatch from yum.plugins import TYPE_INTERACTIVE from yum.plugins import PluginYumExit requires_api_version = '2.0' plugin_type = (TYPE_INTERACTIVE,) def posttrans_hook(conduit):
pkgs = [] patch_required = False # If we aren't root, we can't have updated anything if os.geteuid(): return # See what packages have files that were patched confpkgs = conduit.confString('main', 'packages') if not confpkgs: return tmp = confpkgs.split(",") for confpkg in tmp: pkgs.append(confpkg.strip()) conduit.info(2, "lxc-patch: checking if updated pkgs need patching...") ts = conduit.getTsInfo() for tsmem in ts.getMembers(): for pkg in pkgs: if fnmatch(pkg, tsmem.po.name): patch_required = True if patch_required: conduit.info(2, "lxc-patch: patching container...") os.spawnlp(os.P_WAIT, "lxc-patch", "lxc-patch", "--patch", "/")
identifier_body
lxc-patch.py
# Yum plugin to re-patch container rootfs after a yum update is done # # Copyright (C) 2012 Oracle # # Authors: # Dwight Engen <dwight.engen@oracle.com> # # 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 Library General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # import os from fnmatch import fnmatch from yum.plugins import TYPE_INTERACTIVE from yum.plugins import PluginYumExit requires_api_version = '2.0' plugin_type = (TYPE_INTERACTIVE,) def
(conduit): pkgs = [] patch_required = False # If we aren't root, we can't have updated anything if os.geteuid(): return # See what packages have files that were patched confpkgs = conduit.confString('main', 'packages') if not confpkgs: return tmp = confpkgs.split(",") for confpkg in tmp: pkgs.append(confpkg.strip()) conduit.info(2, "lxc-patch: checking if updated pkgs need patching...") ts = conduit.getTsInfo() for tsmem in ts.getMembers(): for pkg in pkgs: if fnmatch(pkg, tsmem.po.name): patch_required = True if patch_required: conduit.info(2, "lxc-patch: patching container...") os.spawnlp(os.P_WAIT, "lxc-patch", "lxc-patch", "--patch", "/")
posttrans_hook
identifier_name
xls.py
# Rekall Memory Forensics # Copyright 2014 Google Inc. All Rights Reserved. # # Authors: # Michael Cohen <scudette@google.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # """This file implements an xls renderer based on the openpyxl project. We produce xls (Excel spreadsheet files) with the output from Rekall plugins. """ import time import openpyxl from openpyxl import styles from openpyxl.styles import colors from openpyxl.styles import fills from rekall import utils from rekall.ui import renderer from rekall.ui import text # pylint: disable=unexpected-keyword-arg,no-value-for-parameter # pylint: disable=redefined-outer-name HEADER_STYLE = styles.Style(font=styles.Font(bold=True)) SECTION_STYLE = styles.Style( fill=styles.PatternFill( fill_type=fills.FILL_SOLID, start_color=styles.Color(colors.RED))) FORMAT_STYLE = styles.Style( alignment=styles.Alignment(vertical="top", wrap_text=False)) class XLSObjectRenderer(renderer.ObjectRenderer): """By default the XLS renderer delegates to the text renderer.""" renders_type = "object" renderers = ["XLSRenderer"] STYLE = None def _GetDelegateObjectRenderer(self, item):
def RenderHeader(self, worksheet, column): cell = worksheet.cell( row=worksheet.current_row, column=worksheet.current_column) cell.value = column.name cell.style = HEADER_STYLE # Advance the pointer by 1 cell. worksheet.current_column += 1 def RenderCell(self, value, worksheet, **options): # By default just render a single value into the current cell. cell = worksheet.cell( row=worksheet.current_row, column=worksheet.current_column) cell.value = self.GetData(value, **options) if self.STYLE: cell.style = self.STYLE # Advance the pointer by 1 cell. worksheet.current_column += 1 def GetData(self, value, **options): if isinstance(value, (int, float, long)): return value return unicode(self._GetDelegateObjectRenderer(value).render_row( value, **options)) class XLSColumn(text.TextColumn): def __init__(self, type=None, table=None, renderer=None, session=None, **options): super(XLSColumn, self).__init__(table=table, renderer=renderer, session=session, **options) if type: self.object_renderer = self.renderer.get_object_renderer( type=type, target_renderer="XLSRenderer", **options) class XLSTable(text.TextTable): column_class = XLSColumn def render_header(self): current_ws = self.renderer.current_ws for column in self.columns: if column.object_renderer: object_renderer = column.object_renderer else: object_renderer = XLSObjectRenderer( session=self.session, renderer=self.renderer) object_renderer.RenderHeader(self.renderer.current_ws, column) current_ws.current_row += 1 current_ws.current_column = 1 def render_row(self, row=None, highlight=None, **options): merged_opts = self.options.copy() merged_opts.update(options) # Get each column to write its own header. current_ws = self.renderer.current_ws for item in row: # Get the object renderer for the item. object_renderer = self.renderer.get_object_renderer( target=item, type=merged_opts.get("type"), **merged_opts) object_renderer.RenderCell(item, current_ws, **options) current_ws.current_row += 1 current_ws.current_column = 1 class XLSRenderer(renderer.BaseRenderer): """A Renderer for xls files.""" name = "xls" table_class = XLSTable tablesep = "" def __init__(self, output=None, **kwargs): super(XLSRenderer, self).__init__(**kwargs) # Make a single delegate text renderer for reuse. Most of the time we # will just replicate the output from the TextRenderer inside the # spreadsheet cell. self.delegate_text_renderer = text.TextRenderer(session=self.session) self.output = output or self.session.GetParameter("output") # If no output filename was give, just make a name based on the time # stamp. if self.output == None: self.output = "%s.xls" % time.ctime() try: self.wb = openpyxl.load_workbook(self.output) self.current_ws = self.wb.create_sheet() except IOError: self.wb = openpyxl.Workbook() self.current_ws = self.wb.active def start(self, plugin_name=None, kwargs=None): super(XLSRenderer, self).start(plugin_name=plugin_name, kwargs=kwargs) # Make a new worksheet for this run. if self.current_ws is None: self.current_ws = self.wb.create_sheet() ws = self.current_ws ws.title = plugin_name or "" ws.current_row = 1 ws.current_column = 1 return self def flush(self): super(XLSRenderer, self).flush() self.current_ws = None # Write the spreadsheet to a file. self.wb.save(self.output) def section(self, name=None, **_): ws = self.current_ws for i in range(10): cell = ws.cell(row=ws.current_row, column=i + 1) if i == 0: cell.value = name cell.style = SECTION_STYLE ws.current_row += 1 ws.current_column = 1 def format(self, formatstring, *data): worksheet = self.current_ws if "%" in formatstring: data = formatstring % data else: data = formatstring.format(*data) cell = worksheet.cell( row=worksheet.current_row, column=worksheet.current_column) cell.value = data cell.style = FORMAT_STYLE worksheet.current_column += 1 if "\n" in data: worksheet.current_row += 1 worksheet.current_column = 1 def table_header(self, *args, **options): super(XLSRenderer, self).table_header(*args, **options) self.table.render_header() # Following here are object specific renderers. class XLSEProcessRenderer(XLSObjectRenderer): """Expands an EPROCESS into three columns (address, name and PID).""" renders_type = "_EPROCESS" def RenderHeader(self, worksheet, column): for heading in ["_EPROCESS", "Name", "PID"]: cell = worksheet.cell( row=worksheet.current_row, column=worksheet.current_column) cell.value = heading cell.style = HEADER_STYLE worksheet.current_column += 1 def RenderCell(self, item, worksheet, **options): for value in ["%#x" % item.obj_offset, item.name, item.pid]: object_renderer = self.ForTarget(value, self.renderer)( session=self.session, renderer=self.renderer, **options) object_renderer.RenderCell(value, worksheet, **options) class XLSStringRenderer(XLSObjectRenderer): renders_type = "String" def GetData(self, item, **_): return utils.SmartStr(item) class XLSStructRenderer(XLSObjectRenderer): """Hex format struct's offsets.""" renders_type = "Struct" def GetData(self, item, **_): return "%#x" % item.obj_offset class XLSPointerRenderer(XLSObjectRenderer): """Renders the address of the pointer target as a hex string.""" renders_type = "Pointer" def GetData(self, item, **_): result = item.v() if result == None: return "-" return "%#x" % result class XLSNativeTypeRenderer(XLSObjectRenderer): """Renders native types as python objects.""" renders_type = "NativeType" def GetData(self, item, **options): result = item.v() if result != None: return result class XLS_UNICODE_STRING_Renderer(XLSNativeTypeRenderer): renders_type = "_UNICODE_STRING" class XLSNoneObjectRenderer(XLSObjectRenderer): renders_type = "NoneObject" def GetData(self, item, **_): _ = item return "-" class XLSDateTimeRenderer(XLSObjectRenderer): """Renders timestamps as python datetime objects.""" renders_type = "UnixTimeStamp" STYLE = styles.Style(number_format='MM/DD/YYYY HH:MM:SS') def GetData(self, item, **options): if item.v() == 0: return None return item.as_datetime()
return self.ForTarget(item, "TextRenderer")( session=self.session, renderer=self.renderer.delegate_text_renderer)
identifier_body
xls.py
# Rekall Memory Forensics # Copyright 2014 Google Inc. All Rights Reserved. # # Authors: # Michael Cohen <scudette@google.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # """This file implements an xls renderer based on the openpyxl project. We produce xls (Excel spreadsheet files) with the output from Rekall plugins. """ import time import openpyxl
from openpyxl.styles import fills from rekall import utils from rekall.ui import renderer from rekall.ui import text # pylint: disable=unexpected-keyword-arg,no-value-for-parameter # pylint: disable=redefined-outer-name HEADER_STYLE = styles.Style(font=styles.Font(bold=True)) SECTION_STYLE = styles.Style( fill=styles.PatternFill( fill_type=fills.FILL_SOLID, start_color=styles.Color(colors.RED))) FORMAT_STYLE = styles.Style( alignment=styles.Alignment(vertical="top", wrap_text=False)) class XLSObjectRenderer(renderer.ObjectRenderer): """By default the XLS renderer delegates to the text renderer.""" renders_type = "object" renderers = ["XLSRenderer"] STYLE = None def _GetDelegateObjectRenderer(self, item): return self.ForTarget(item, "TextRenderer")( session=self.session, renderer=self.renderer.delegate_text_renderer) def RenderHeader(self, worksheet, column): cell = worksheet.cell( row=worksheet.current_row, column=worksheet.current_column) cell.value = column.name cell.style = HEADER_STYLE # Advance the pointer by 1 cell. worksheet.current_column += 1 def RenderCell(self, value, worksheet, **options): # By default just render a single value into the current cell. cell = worksheet.cell( row=worksheet.current_row, column=worksheet.current_column) cell.value = self.GetData(value, **options) if self.STYLE: cell.style = self.STYLE # Advance the pointer by 1 cell. worksheet.current_column += 1 def GetData(self, value, **options): if isinstance(value, (int, float, long)): return value return unicode(self._GetDelegateObjectRenderer(value).render_row( value, **options)) class XLSColumn(text.TextColumn): def __init__(self, type=None, table=None, renderer=None, session=None, **options): super(XLSColumn, self).__init__(table=table, renderer=renderer, session=session, **options) if type: self.object_renderer = self.renderer.get_object_renderer( type=type, target_renderer="XLSRenderer", **options) class XLSTable(text.TextTable): column_class = XLSColumn def render_header(self): current_ws = self.renderer.current_ws for column in self.columns: if column.object_renderer: object_renderer = column.object_renderer else: object_renderer = XLSObjectRenderer( session=self.session, renderer=self.renderer) object_renderer.RenderHeader(self.renderer.current_ws, column) current_ws.current_row += 1 current_ws.current_column = 1 def render_row(self, row=None, highlight=None, **options): merged_opts = self.options.copy() merged_opts.update(options) # Get each column to write its own header. current_ws = self.renderer.current_ws for item in row: # Get the object renderer for the item. object_renderer = self.renderer.get_object_renderer( target=item, type=merged_opts.get("type"), **merged_opts) object_renderer.RenderCell(item, current_ws, **options) current_ws.current_row += 1 current_ws.current_column = 1 class XLSRenderer(renderer.BaseRenderer): """A Renderer for xls files.""" name = "xls" table_class = XLSTable tablesep = "" def __init__(self, output=None, **kwargs): super(XLSRenderer, self).__init__(**kwargs) # Make a single delegate text renderer for reuse. Most of the time we # will just replicate the output from the TextRenderer inside the # spreadsheet cell. self.delegate_text_renderer = text.TextRenderer(session=self.session) self.output = output or self.session.GetParameter("output") # If no output filename was give, just make a name based on the time # stamp. if self.output == None: self.output = "%s.xls" % time.ctime() try: self.wb = openpyxl.load_workbook(self.output) self.current_ws = self.wb.create_sheet() except IOError: self.wb = openpyxl.Workbook() self.current_ws = self.wb.active def start(self, plugin_name=None, kwargs=None): super(XLSRenderer, self).start(plugin_name=plugin_name, kwargs=kwargs) # Make a new worksheet for this run. if self.current_ws is None: self.current_ws = self.wb.create_sheet() ws = self.current_ws ws.title = plugin_name or "" ws.current_row = 1 ws.current_column = 1 return self def flush(self): super(XLSRenderer, self).flush() self.current_ws = None # Write the spreadsheet to a file. self.wb.save(self.output) def section(self, name=None, **_): ws = self.current_ws for i in range(10): cell = ws.cell(row=ws.current_row, column=i + 1) if i == 0: cell.value = name cell.style = SECTION_STYLE ws.current_row += 1 ws.current_column = 1 def format(self, formatstring, *data): worksheet = self.current_ws if "%" in formatstring: data = formatstring % data else: data = formatstring.format(*data) cell = worksheet.cell( row=worksheet.current_row, column=worksheet.current_column) cell.value = data cell.style = FORMAT_STYLE worksheet.current_column += 1 if "\n" in data: worksheet.current_row += 1 worksheet.current_column = 1 def table_header(self, *args, **options): super(XLSRenderer, self).table_header(*args, **options) self.table.render_header() # Following here are object specific renderers. class XLSEProcessRenderer(XLSObjectRenderer): """Expands an EPROCESS into three columns (address, name and PID).""" renders_type = "_EPROCESS" def RenderHeader(self, worksheet, column): for heading in ["_EPROCESS", "Name", "PID"]: cell = worksheet.cell( row=worksheet.current_row, column=worksheet.current_column) cell.value = heading cell.style = HEADER_STYLE worksheet.current_column += 1 def RenderCell(self, item, worksheet, **options): for value in ["%#x" % item.obj_offset, item.name, item.pid]: object_renderer = self.ForTarget(value, self.renderer)( session=self.session, renderer=self.renderer, **options) object_renderer.RenderCell(value, worksheet, **options) class XLSStringRenderer(XLSObjectRenderer): renders_type = "String" def GetData(self, item, **_): return utils.SmartStr(item) class XLSStructRenderer(XLSObjectRenderer): """Hex format struct's offsets.""" renders_type = "Struct" def GetData(self, item, **_): return "%#x" % item.obj_offset class XLSPointerRenderer(XLSObjectRenderer): """Renders the address of the pointer target as a hex string.""" renders_type = "Pointer" def GetData(self, item, **_): result = item.v() if result == None: return "-" return "%#x" % result class XLSNativeTypeRenderer(XLSObjectRenderer): """Renders native types as python objects.""" renders_type = "NativeType" def GetData(self, item, **options): result = item.v() if result != None: return result class XLS_UNICODE_STRING_Renderer(XLSNativeTypeRenderer): renders_type = "_UNICODE_STRING" class XLSNoneObjectRenderer(XLSObjectRenderer): renders_type = "NoneObject" def GetData(self, item, **_): _ = item return "-" class XLSDateTimeRenderer(XLSObjectRenderer): """Renders timestamps as python datetime objects.""" renders_type = "UnixTimeStamp" STYLE = styles.Style(number_format='MM/DD/YYYY HH:MM:SS') def GetData(self, item, **options): if item.v() == 0: return None return item.as_datetime()
from openpyxl import styles from openpyxl.styles import colors
random_line_split
xls.py
# Rekall Memory Forensics # Copyright 2014 Google Inc. All Rights Reserved. # # Authors: # Michael Cohen <scudette@google.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # """This file implements an xls renderer based on the openpyxl project. We produce xls (Excel spreadsheet files) with the output from Rekall plugins. """ import time import openpyxl from openpyxl import styles from openpyxl.styles import colors from openpyxl.styles import fills from rekall import utils from rekall.ui import renderer from rekall.ui import text # pylint: disable=unexpected-keyword-arg,no-value-for-parameter # pylint: disable=redefined-outer-name HEADER_STYLE = styles.Style(font=styles.Font(bold=True)) SECTION_STYLE = styles.Style( fill=styles.PatternFill( fill_type=fills.FILL_SOLID, start_color=styles.Color(colors.RED))) FORMAT_STYLE = styles.Style( alignment=styles.Alignment(vertical="top", wrap_text=False)) class XLSObjectRenderer(renderer.ObjectRenderer): """By default the XLS renderer delegates to the text renderer.""" renders_type = "object" renderers = ["XLSRenderer"] STYLE = None def _GetDelegateObjectRenderer(self, item): return self.ForTarget(item, "TextRenderer")( session=self.session, renderer=self.renderer.delegate_text_renderer) def RenderHeader(self, worksheet, column): cell = worksheet.cell( row=worksheet.current_row, column=worksheet.current_column) cell.value = column.name cell.style = HEADER_STYLE # Advance the pointer by 1 cell. worksheet.current_column += 1 def RenderCell(self, value, worksheet, **options): # By default just render a single value into the current cell. cell = worksheet.cell( row=worksheet.current_row, column=worksheet.current_column) cell.value = self.GetData(value, **options) if self.STYLE: cell.style = self.STYLE # Advance the pointer by 1 cell. worksheet.current_column += 1 def GetData(self, value, **options): if isinstance(value, (int, float, long)): return value return unicode(self._GetDelegateObjectRenderer(value).render_row( value, **options)) class
(text.TextColumn): def __init__(self, type=None, table=None, renderer=None, session=None, **options): super(XLSColumn, self).__init__(table=table, renderer=renderer, session=session, **options) if type: self.object_renderer = self.renderer.get_object_renderer( type=type, target_renderer="XLSRenderer", **options) class XLSTable(text.TextTable): column_class = XLSColumn def render_header(self): current_ws = self.renderer.current_ws for column in self.columns: if column.object_renderer: object_renderer = column.object_renderer else: object_renderer = XLSObjectRenderer( session=self.session, renderer=self.renderer) object_renderer.RenderHeader(self.renderer.current_ws, column) current_ws.current_row += 1 current_ws.current_column = 1 def render_row(self, row=None, highlight=None, **options): merged_opts = self.options.copy() merged_opts.update(options) # Get each column to write its own header. current_ws = self.renderer.current_ws for item in row: # Get the object renderer for the item. object_renderer = self.renderer.get_object_renderer( target=item, type=merged_opts.get("type"), **merged_opts) object_renderer.RenderCell(item, current_ws, **options) current_ws.current_row += 1 current_ws.current_column = 1 class XLSRenderer(renderer.BaseRenderer): """A Renderer for xls files.""" name = "xls" table_class = XLSTable tablesep = "" def __init__(self, output=None, **kwargs): super(XLSRenderer, self).__init__(**kwargs) # Make a single delegate text renderer for reuse. Most of the time we # will just replicate the output from the TextRenderer inside the # spreadsheet cell. self.delegate_text_renderer = text.TextRenderer(session=self.session) self.output = output or self.session.GetParameter("output") # If no output filename was give, just make a name based on the time # stamp. if self.output == None: self.output = "%s.xls" % time.ctime() try: self.wb = openpyxl.load_workbook(self.output) self.current_ws = self.wb.create_sheet() except IOError: self.wb = openpyxl.Workbook() self.current_ws = self.wb.active def start(self, plugin_name=None, kwargs=None): super(XLSRenderer, self).start(plugin_name=plugin_name, kwargs=kwargs) # Make a new worksheet for this run. if self.current_ws is None: self.current_ws = self.wb.create_sheet() ws = self.current_ws ws.title = plugin_name or "" ws.current_row = 1 ws.current_column = 1 return self def flush(self): super(XLSRenderer, self).flush() self.current_ws = None # Write the spreadsheet to a file. self.wb.save(self.output) def section(self, name=None, **_): ws = self.current_ws for i in range(10): cell = ws.cell(row=ws.current_row, column=i + 1) if i == 0: cell.value = name cell.style = SECTION_STYLE ws.current_row += 1 ws.current_column = 1 def format(self, formatstring, *data): worksheet = self.current_ws if "%" in formatstring: data = formatstring % data else: data = formatstring.format(*data) cell = worksheet.cell( row=worksheet.current_row, column=worksheet.current_column) cell.value = data cell.style = FORMAT_STYLE worksheet.current_column += 1 if "\n" in data: worksheet.current_row += 1 worksheet.current_column = 1 def table_header(self, *args, **options): super(XLSRenderer, self).table_header(*args, **options) self.table.render_header() # Following here are object specific renderers. class XLSEProcessRenderer(XLSObjectRenderer): """Expands an EPROCESS into three columns (address, name and PID).""" renders_type = "_EPROCESS" def RenderHeader(self, worksheet, column): for heading in ["_EPROCESS", "Name", "PID"]: cell = worksheet.cell( row=worksheet.current_row, column=worksheet.current_column) cell.value = heading cell.style = HEADER_STYLE worksheet.current_column += 1 def RenderCell(self, item, worksheet, **options): for value in ["%#x" % item.obj_offset, item.name, item.pid]: object_renderer = self.ForTarget(value, self.renderer)( session=self.session, renderer=self.renderer, **options) object_renderer.RenderCell(value, worksheet, **options) class XLSStringRenderer(XLSObjectRenderer): renders_type = "String" def GetData(self, item, **_): return utils.SmartStr(item) class XLSStructRenderer(XLSObjectRenderer): """Hex format struct's offsets.""" renders_type = "Struct" def GetData(self, item, **_): return "%#x" % item.obj_offset class XLSPointerRenderer(XLSObjectRenderer): """Renders the address of the pointer target as a hex string.""" renders_type = "Pointer" def GetData(self, item, **_): result = item.v() if result == None: return "-" return "%#x" % result class XLSNativeTypeRenderer(XLSObjectRenderer): """Renders native types as python objects.""" renders_type = "NativeType" def GetData(self, item, **options): result = item.v() if result != None: return result class XLS_UNICODE_STRING_Renderer(XLSNativeTypeRenderer): renders_type = "_UNICODE_STRING" class XLSNoneObjectRenderer(XLSObjectRenderer): renders_type = "NoneObject" def GetData(self, item, **_): _ = item return "-" class XLSDateTimeRenderer(XLSObjectRenderer): """Renders timestamps as python datetime objects.""" renders_type = "UnixTimeStamp" STYLE = styles.Style(number_format='MM/DD/YYYY HH:MM:SS') def GetData(self, item, **options): if item.v() == 0: return None return item.as_datetime()
XLSColumn
identifier_name
xls.py
# Rekall Memory Forensics # Copyright 2014 Google Inc. All Rights Reserved. # # Authors: # Michael Cohen <scudette@google.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # """This file implements an xls renderer based on the openpyxl project. We produce xls (Excel spreadsheet files) with the output from Rekall plugins. """ import time import openpyxl from openpyxl import styles from openpyxl.styles import colors from openpyxl.styles import fills from rekall import utils from rekall.ui import renderer from rekall.ui import text # pylint: disable=unexpected-keyword-arg,no-value-for-parameter # pylint: disable=redefined-outer-name HEADER_STYLE = styles.Style(font=styles.Font(bold=True)) SECTION_STYLE = styles.Style( fill=styles.PatternFill( fill_type=fills.FILL_SOLID, start_color=styles.Color(colors.RED))) FORMAT_STYLE = styles.Style( alignment=styles.Alignment(vertical="top", wrap_text=False)) class XLSObjectRenderer(renderer.ObjectRenderer): """By default the XLS renderer delegates to the text renderer.""" renders_type = "object" renderers = ["XLSRenderer"] STYLE = None def _GetDelegateObjectRenderer(self, item): return self.ForTarget(item, "TextRenderer")( session=self.session, renderer=self.renderer.delegate_text_renderer) def RenderHeader(self, worksheet, column): cell = worksheet.cell( row=worksheet.current_row, column=worksheet.current_column) cell.value = column.name cell.style = HEADER_STYLE # Advance the pointer by 1 cell. worksheet.current_column += 1 def RenderCell(self, value, worksheet, **options): # By default just render a single value into the current cell. cell = worksheet.cell( row=worksheet.current_row, column=worksheet.current_column) cell.value = self.GetData(value, **options) if self.STYLE: cell.style = self.STYLE # Advance the pointer by 1 cell. worksheet.current_column += 1 def GetData(self, value, **options): if isinstance(value, (int, float, long)): return value return unicode(self._GetDelegateObjectRenderer(value).render_row( value, **options)) class XLSColumn(text.TextColumn): def __init__(self, type=None, table=None, renderer=None, session=None, **options): super(XLSColumn, self).__init__(table=table, renderer=renderer, session=session, **options) if type: self.object_renderer = self.renderer.get_object_renderer( type=type, target_renderer="XLSRenderer", **options) class XLSTable(text.TextTable): column_class = XLSColumn def render_header(self): current_ws = self.renderer.current_ws for column in self.columns: if column.object_renderer: object_renderer = column.object_renderer else: object_renderer = XLSObjectRenderer( session=self.session, renderer=self.renderer) object_renderer.RenderHeader(self.renderer.current_ws, column) current_ws.current_row += 1 current_ws.current_column = 1 def render_row(self, row=None, highlight=None, **options): merged_opts = self.options.copy() merged_opts.update(options) # Get each column to write its own header. current_ws = self.renderer.current_ws for item in row: # Get the object renderer for the item. object_renderer = self.renderer.get_object_renderer( target=item, type=merged_opts.get("type"), **merged_opts) object_renderer.RenderCell(item, current_ws, **options) current_ws.current_row += 1 current_ws.current_column = 1 class XLSRenderer(renderer.BaseRenderer): """A Renderer for xls files.""" name = "xls" table_class = XLSTable tablesep = "" def __init__(self, output=None, **kwargs): super(XLSRenderer, self).__init__(**kwargs) # Make a single delegate text renderer for reuse. Most of the time we # will just replicate the output from the TextRenderer inside the # spreadsheet cell. self.delegate_text_renderer = text.TextRenderer(session=self.session) self.output = output or self.session.GetParameter("output") # If no output filename was give, just make a name based on the time # stamp. if self.output == None: self.output = "%s.xls" % time.ctime() try: self.wb = openpyxl.load_workbook(self.output) self.current_ws = self.wb.create_sheet() except IOError: self.wb = openpyxl.Workbook() self.current_ws = self.wb.active def start(self, plugin_name=None, kwargs=None): super(XLSRenderer, self).start(plugin_name=plugin_name, kwargs=kwargs) # Make a new worksheet for this run. if self.current_ws is None: self.current_ws = self.wb.create_sheet() ws = self.current_ws ws.title = plugin_name or "" ws.current_row = 1 ws.current_column = 1 return self def flush(self): super(XLSRenderer, self).flush() self.current_ws = None # Write the spreadsheet to a file. self.wb.save(self.output) def section(self, name=None, **_): ws = self.current_ws for i in range(10): cell = ws.cell(row=ws.current_row, column=i + 1) if i == 0: cell.value = name cell.style = SECTION_STYLE ws.current_row += 1 ws.current_column = 1 def format(self, formatstring, *data): worksheet = self.current_ws if "%" in formatstring: data = formatstring % data else: data = formatstring.format(*data) cell = worksheet.cell( row=worksheet.current_row, column=worksheet.current_column) cell.value = data cell.style = FORMAT_STYLE worksheet.current_column += 1 if "\n" in data:
def table_header(self, *args, **options): super(XLSRenderer, self).table_header(*args, **options) self.table.render_header() # Following here are object specific renderers. class XLSEProcessRenderer(XLSObjectRenderer): """Expands an EPROCESS into three columns (address, name and PID).""" renders_type = "_EPROCESS" def RenderHeader(self, worksheet, column): for heading in ["_EPROCESS", "Name", "PID"]: cell = worksheet.cell( row=worksheet.current_row, column=worksheet.current_column) cell.value = heading cell.style = HEADER_STYLE worksheet.current_column += 1 def RenderCell(self, item, worksheet, **options): for value in ["%#x" % item.obj_offset, item.name, item.pid]: object_renderer = self.ForTarget(value, self.renderer)( session=self.session, renderer=self.renderer, **options) object_renderer.RenderCell(value, worksheet, **options) class XLSStringRenderer(XLSObjectRenderer): renders_type = "String" def GetData(self, item, **_): return utils.SmartStr(item) class XLSStructRenderer(XLSObjectRenderer): """Hex format struct's offsets.""" renders_type = "Struct" def GetData(self, item, **_): return "%#x" % item.obj_offset class XLSPointerRenderer(XLSObjectRenderer): """Renders the address of the pointer target as a hex string.""" renders_type = "Pointer" def GetData(self, item, **_): result = item.v() if result == None: return "-" return "%#x" % result class XLSNativeTypeRenderer(XLSObjectRenderer): """Renders native types as python objects.""" renders_type = "NativeType" def GetData(self, item, **options): result = item.v() if result != None: return result class XLS_UNICODE_STRING_Renderer(XLSNativeTypeRenderer): renders_type = "_UNICODE_STRING" class XLSNoneObjectRenderer(XLSObjectRenderer): renders_type = "NoneObject" def GetData(self, item, **_): _ = item return "-" class XLSDateTimeRenderer(XLSObjectRenderer): """Renders timestamps as python datetime objects.""" renders_type = "UnixTimeStamp" STYLE = styles.Style(number_format='MM/DD/YYYY HH:MM:SS') def GetData(self, item, **options): if item.v() == 0: return None return item.as_datetime()
worksheet.current_row += 1 worksheet.current_column = 1
conditional_block
utils.py
def copy_files(src, target_node, parent=None, name=None):
"""Copy the files from src to the target node :param Folder src: The source to copy children from :param Node target_node: The node to copy files to :param Folder parent: The parent of to attach the clone of src to, if applicable """ assert not parent or not parent.is_file, 'Parent must be a folder' cloned = src.clone() cloned.parent = parent cloned.target = target_node cloned.name = name or cloned.name cloned.copied_from = src cloned.save() if src.is_file and src.versions.exists(): fileversions = src.versions.select_related('region').order_by('-created') most_recent_fileversion = fileversions.first() if most_recent_fileversion.region and most_recent_fileversion.region != target_node.osfstorage_region: # add all original version except the most recent cloned.versions.add(*fileversions[1:]) # create a new most recent version and update the region before adding new_fileversion = most_recent_fileversion.clone() new_fileversion.region = target_node.osfstorage_region new_fileversion.save() cloned.versions.add(new_fileversion) else: cloned.versions.add(*src.versions.all()) # copy over file metadata records if cloned.provider == 'osfstorage': for record in cloned.records.all(): record.metadata = src.records.get(schema__name=record.schema.name).metadata record.save() if not src.is_file: for child in src.children: copy_files(child, target_node, parent=cloned) return cloned
identifier_body
utils.py
def copy_files(src, target_node, parent=None, name=None): """Copy the files from src to the target node :param Folder src: The source to copy children from :param Node target_node: The node to copy files to :param Folder parent: The parent of to attach the clone of src to, if applicable """ assert not parent or not parent.is_file, 'Parent must be a folder' cloned = src.clone() cloned.parent = parent cloned.target = target_node cloned.name = name or cloned.name cloned.copied_from = src cloned.save() if src.is_file and src.versions.exists(): fileversions = src.versions.select_related('region').order_by('-created') most_recent_fileversion = fileversions.first() if most_recent_fileversion.region and most_recent_fileversion.region != target_node.osfstorage_region: # add all original version except the most recent cloned.versions.add(*fileversions[1:]) # create a new most recent version and update the region before adding new_fileversion = most_recent_fileversion.clone() new_fileversion.region = target_node.osfstorage_region new_fileversion.save() cloned.versions.add(new_fileversion) else: cloned.versions.add(*src.versions.all()) # copy over file metadata records if cloned.provider == 'osfstorage': for record in cloned.records.all():
for child in src.children: copy_files(child, target_node, parent=cloned) return cloned
record.metadata = src.records.get(schema__name=record.schema.name).metadata record.save() if not src.is_file:
random_line_split
utils.py
def copy_files(src, target_node, parent=None, name=None): """Copy the files from src to the target node :param Folder src: The source to copy children from :param Node target_node: The node to copy files to :param Folder parent: The parent of to attach the clone of src to, if applicable """ assert not parent or not parent.is_file, 'Parent must be a folder' cloned = src.clone() cloned.parent = parent cloned.target = target_node cloned.name = name or cloned.name cloned.copied_from = src cloned.save() if src.is_file and src.versions.exists(): fileversions = src.versions.select_related('region').order_by('-created') most_recent_fileversion = fileversions.first() if most_recent_fileversion.region and most_recent_fileversion.region != target_node.osfstorage_region: # add all original version except the most recent cloned.versions.add(*fileversions[1:]) # create a new most recent version and update the region before adding new_fileversion = most_recent_fileversion.clone() new_fileversion.region = target_node.osfstorage_region new_fileversion.save() cloned.versions.add(new_fileversion) else:
# copy over file metadata records if cloned.provider == 'osfstorage': for record in cloned.records.all(): record.metadata = src.records.get(schema__name=record.schema.name).metadata record.save() if not src.is_file: for child in src.children: copy_files(child, target_node, parent=cloned) return cloned
cloned.versions.add(*src.versions.all())
conditional_block
utils.py
def
(src, target_node, parent=None, name=None): """Copy the files from src to the target node :param Folder src: The source to copy children from :param Node target_node: The node to copy files to :param Folder parent: The parent of to attach the clone of src to, if applicable """ assert not parent or not parent.is_file, 'Parent must be a folder' cloned = src.clone() cloned.parent = parent cloned.target = target_node cloned.name = name or cloned.name cloned.copied_from = src cloned.save() if src.is_file and src.versions.exists(): fileversions = src.versions.select_related('region').order_by('-created') most_recent_fileversion = fileversions.first() if most_recent_fileversion.region and most_recent_fileversion.region != target_node.osfstorage_region: # add all original version except the most recent cloned.versions.add(*fileversions[1:]) # create a new most recent version and update the region before adding new_fileversion = most_recent_fileversion.clone() new_fileversion.region = target_node.osfstorage_region new_fileversion.save() cloned.versions.add(new_fileversion) else: cloned.versions.add(*src.versions.all()) # copy over file metadata records if cloned.provider == 'osfstorage': for record in cloned.records.all(): record.metadata = src.records.get(schema__name=record.schema.name).metadata record.save() if not src.is_file: for child in src.children: copy_files(child, target_node, parent=cloned) return cloned
copy_files
identifier_name
DateRangePickerDay.test.tsx
import * as React from 'react'; import { describeConformanceV5 } from 'test/utils'; import DateRangePickerDay, { dateRangePickerDayClasses as classes, } from '@material-ui/lab/DateRangePickerDay'; import { adapterToUse, wrapPickerMount, createPickerRender } from '../internal/pickers/test-utils'; describe('<DateRangePickerDay />', () => { const render = createPickerRender(); describeConformanceV5( <DateRangePickerDay day={adapterToUse.date()} outsideCurrentMonth={false} selected onDaySelect={() => {}} isHighlighting isPreviewing isStartOfPreviewing isEndOfPreviewing isStartOfHighlighting isEndOfHighlighting />, () => ({ classes, inheritComponent: 'button', muiName: 'MuiDateRangePickerDay', render, wrapMount: wrapPickerMount, refInstanceof: window.HTMLButtonElement, // cannot test reactTestRenderer because of required context skip: [ 'componentProp',
// TODO: Fix DateRangePickerDays is not spreading props on root 'themeDefaultProps', 'themeVariants', ], }), ); });
'componentsProp', 'reactTestRenderer', 'propsSpread', 'refForwarding',
random_line_split
rpc_misc.py
#!/usr/bin/env python3 # Copyright (c) 2019-2021 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test RPC misc output.""" import xml.etree.ElementTree as ET from test_framework.test_framework import SyscoinTestFramework from test_framework.util import ( assert_raises_rpc_error, assert_equal, assert_greater_than, assert_greater_than_or_equal, ) from test_framework.authproxy import JSONRPCException class RpcMiscTest(SyscoinTestFramework): def set_test_params(self): self.num_nodes = 1 self.supports_cli = False def run_test(self): node = self.nodes[0] self.log.info("test CHECK_NONFATAL") assert_raises_rpc_error( -1, 'Internal bug detected: \'request.params[9].get_str() != "trigger_internal_bug"\'', lambda: node.echo(arg9='trigger_internal_bug'), ) self.log.info("test getmemoryinfo") memory = node.getmemoryinfo()['locked'] assert_greater_than(memory['used'], 0) assert_greater_than(memory['free'], 0) assert_greater_than(memory['total'], 0) # assert_greater_than_or_equal() for locked in case locking pages failed at some point assert_greater_than_or_equal(memory['locked'], 0) assert_greater_than(memory['chunks_used'], 0) assert_greater_than(memory['chunks_free'], 0) assert_equal(memory['used'] + memory['free'], memory['total']) self.log.info("test mallocinfo") try: mallocinfo = node.getmemoryinfo(mode="mallocinfo") self.log.info('getmemoryinfo(mode="mallocinfo") call succeeded') tree = ET.fromstring(mallocinfo) assert_equal(tree.tag, 'malloc') except JSONRPCException: self.log.info('getmemoryinfo(mode="mallocinfo") not available') assert_raises_rpc_error(-8, 'mallocinfo is only available when compiled with glibc 2.10+', node.getmemoryinfo, mode="mallocinfo") assert_raises_rpc_error(-8, "unknown mode foobar", node.getmemoryinfo, mode="foobar") self.log.info("test logging rpc and help") # SYSCOIN Test logging RPC returns the expected number of logging categories. assert_equal(len(node.logging()), 36) # Test toggling a logging category on/off/on with the logging RPC. assert_equal(node.logging()['qt'], True) node.logging(exclude=['qt']) assert_equal(node.logging()['qt'], False) node.logging(include=['qt']) assert_equal(node.logging()['qt'], True) # Test logging RPC returns the logging categories in alphabetical order. sorted_logging_categories = sorted(node.logging()) assert_equal(list(node.logging()), sorted_logging_categories) # Test logging help returns the logging categories string in alphabetical order. categories = ', '.join(sorted_logging_categories)
self.log.info("test echoipc (testing spawned process in multiprocess build)") assert_equal(node.echoipc("hello"), "hello") self.log.info("test getindexinfo") # Without any indices running the RPC returns an empty object assert_equal(node.getindexinfo(), {}) # Restart the node with indices and wait for them to sync self.restart_node(0, ["-txindex", "-blockfilterindex", "-coinstatsindex"]) self.wait_until(lambda: all(i["synced"] for i in node.getindexinfo().values())) # Returns a list of all running indices by default values = {"synced": True, "best_block_height": 200} assert_equal( node.getindexinfo(), { "txindex": values, "basic block filter index": values, "coinstatsindex": values, } ) # Specifying an index by name returns only the status of that index for i in {"txindex", "basic block filter index", "coinstatsindex"}: assert_equal(node.getindexinfo(i), {i: values}) # Specifying an unknown index name returns an empty result assert_equal(node.getindexinfo("foo"), {}) if __name__ == '__main__': RpcMiscTest().main()
logging_help = self.nodes[0].help('logging') assert f"valid logging categories are: {categories}" in logging_help
random_line_split
rpc_misc.py
#!/usr/bin/env python3 # Copyright (c) 2019-2021 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test RPC misc output.""" import xml.etree.ElementTree as ET from test_framework.test_framework import SyscoinTestFramework from test_framework.util import ( assert_raises_rpc_error, assert_equal, assert_greater_than, assert_greater_than_or_equal, ) from test_framework.authproxy import JSONRPCException class RpcMiscTest(SyscoinTestFramework): def set_test_params(self): self.num_nodes = 1 self.supports_cli = False def run_test(self):
if __name__ == '__main__': RpcMiscTest().main()
node = self.nodes[0] self.log.info("test CHECK_NONFATAL") assert_raises_rpc_error( -1, 'Internal bug detected: \'request.params[9].get_str() != "trigger_internal_bug"\'', lambda: node.echo(arg9='trigger_internal_bug'), ) self.log.info("test getmemoryinfo") memory = node.getmemoryinfo()['locked'] assert_greater_than(memory['used'], 0) assert_greater_than(memory['free'], 0) assert_greater_than(memory['total'], 0) # assert_greater_than_or_equal() for locked in case locking pages failed at some point assert_greater_than_or_equal(memory['locked'], 0) assert_greater_than(memory['chunks_used'], 0) assert_greater_than(memory['chunks_free'], 0) assert_equal(memory['used'] + memory['free'], memory['total']) self.log.info("test mallocinfo") try: mallocinfo = node.getmemoryinfo(mode="mallocinfo") self.log.info('getmemoryinfo(mode="mallocinfo") call succeeded') tree = ET.fromstring(mallocinfo) assert_equal(tree.tag, 'malloc') except JSONRPCException: self.log.info('getmemoryinfo(mode="mallocinfo") not available') assert_raises_rpc_error(-8, 'mallocinfo is only available when compiled with glibc 2.10+', node.getmemoryinfo, mode="mallocinfo") assert_raises_rpc_error(-8, "unknown mode foobar", node.getmemoryinfo, mode="foobar") self.log.info("test logging rpc and help") # SYSCOIN Test logging RPC returns the expected number of logging categories. assert_equal(len(node.logging()), 36) # Test toggling a logging category on/off/on with the logging RPC. assert_equal(node.logging()['qt'], True) node.logging(exclude=['qt']) assert_equal(node.logging()['qt'], False) node.logging(include=['qt']) assert_equal(node.logging()['qt'], True) # Test logging RPC returns the logging categories in alphabetical order. sorted_logging_categories = sorted(node.logging()) assert_equal(list(node.logging()), sorted_logging_categories) # Test logging help returns the logging categories string in alphabetical order. categories = ', '.join(sorted_logging_categories) logging_help = self.nodes[0].help('logging') assert f"valid logging categories are: {categories}" in logging_help self.log.info("test echoipc (testing spawned process in multiprocess build)") assert_equal(node.echoipc("hello"), "hello") self.log.info("test getindexinfo") # Without any indices running the RPC returns an empty object assert_equal(node.getindexinfo(), {}) # Restart the node with indices and wait for them to sync self.restart_node(0, ["-txindex", "-blockfilterindex", "-coinstatsindex"]) self.wait_until(lambda: all(i["synced"] for i in node.getindexinfo().values())) # Returns a list of all running indices by default values = {"synced": True, "best_block_height": 200} assert_equal( node.getindexinfo(), { "txindex": values, "basic block filter index": values, "coinstatsindex": values, } ) # Specifying an index by name returns only the status of that index for i in {"txindex", "basic block filter index", "coinstatsindex"}: assert_equal(node.getindexinfo(i), {i: values}) # Specifying an unknown index name returns an empty result assert_equal(node.getindexinfo("foo"), {})
identifier_body
rpc_misc.py
#!/usr/bin/env python3 # Copyright (c) 2019-2021 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test RPC misc output.""" import xml.etree.ElementTree as ET from test_framework.test_framework import SyscoinTestFramework from test_framework.util import ( assert_raises_rpc_error, assert_equal, assert_greater_than, assert_greater_than_or_equal, ) from test_framework.authproxy import JSONRPCException class
(SyscoinTestFramework): def set_test_params(self): self.num_nodes = 1 self.supports_cli = False def run_test(self): node = self.nodes[0] self.log.info("test CHECK_NONFATAL") assert_raises_rpc_error( -1, 'Internal bug detected: \'request.params[9].get_str() != "trigger_internal_bug"\'', lambda: node.echo(arg9='trigger_internal_bug'), ) self.log.info("test getmemoryinfo") memory = node.getmemoryinfo()['locked'] assert_greater_than(memory['used'], 0) assert_greater_than(memory['free'], 0) assert_greater_than(memory['total'], 0) # assert_greater_than_or_equal() for locked in case locking pages failed at some point assert_greater_than_or_equal(memory['locked'], 0) assert_greater_than(memory['chunks_used'], 0) assert_greater_than(memory['chunks_free'], 0) assert_equal(memory['used'] + memory['free'], memory['total']) self.log.info("test mallocinfo") try: mallocinfo = node.getmemoryinfo(mode="mallocinfo") self.log.info('getmemoryinfo(mode="mallocinfo") call succeeded') tree = ET.fromstring(mallocinfo) assert_equal(tree.tag, 'malloc') except JSONRPCException: self.log.info('getmemoryinfo(mode="mallocinfo") not available') assert_raises_rpc_error(-8, 'mallocinfo is only available when compiled with glibc 2.10+', node.getmemoryinfo, mode="mallocinfo") assert_raises_rpc_error(-8, "unknown mode foobar", node.getmemoryinfo, mode="foobar") self.log.info("test logging rpc and help") # SYSCOIN Test logging RPC returns the expected number of logging categories. assert_equal(len(node.logging()), 36) # Test toggling a logging category on/off/on with the logging RPC. assert_equal(node.logging()['qt'], True) node.logging(exclude=['qt']) assert_equal(node.logging()['qt'], False) node.logging(include=['qt']) assert_equal(node.logging()['qt'], True) # Test logging RPC returns the logging categories in alphabetical order. sorted_logging_categories = sorted(node.logging()) assert_equal(list(node.logging()), sorted_logging_categories) # Test logging help returns the logging categories string in alphabetical order. categories = ', '.join(sorted_logging_categories) logging_help = self.nodes[0].help('logging') assert f"valid logging categories are: {categories}" in logging_help self.log.info("test echoipc (testing spawned process in multiprocess build)") assert_equal(node.echoipc("hello"), "hello") self.log.info("test getindexinfo") # Without any indices running the RPC returns an empty object assert_equal(node.getindexinfo(), {}) # Restart the node with indices and wait for them to sync self.restart_node(0, ["-txindex", "-blockfilterindex", "-coinstatsindex"]) self.wait_until(lambda: all(i["synced"] for i in node.getindexinfo().values())) # Returns a list of all running indices by default values = {"synced": True, "best_block_height": 200} assert_equal( node.getindexinfo(), { "txindex": values, "basic block filter index": values, "coinstatsindex": values, } ) # Specifying an index by name returns only the status of that index for i in {"txindex", "basic block filter index", "coinstatsindex"}: assert_equal(node.getindexinfo(i), {i: values}) # Specifying an unknown index name returns an empty result assert_equal(node.getindexinfo("foo"), {}) if __name__ == '__main__': RpcMiscTest().main()
RpcMiscTest
identifier_name
rpc_misc.py
#!/usr/bin/env python3 # Copyright (c) 2019-2021 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test RPC misc output.""" import xml.etree.ElementTree as ET from test_framework.test_framework import SyscoinTestFramework from test_framework.util import ( assert_raises_rpc_error, assert_equal, assert_greater_than, assert_greater_than_or_equal, ) from test_framework.authproxy import JSONRPCException class RpcMiscTest(SyscoinTestFramework): def set_test_params(self): self.num_nodes = 1 self.supports_cli = False def run_test(self): node = self.nodes[0] self.log.info("test CHECK_NONFATAL") assert_raises_rpc_error( -1, 'Internal bug detected: \'request.params[9].get_str() != "trigger_internal_bug"\'', lambda: node.echo(arg9='trigger_internal_bug'), ) self.log.info("test getmemoryinfo") memory = node.getmemoryinfo()['locked'] assert_greater_than(memory['used'], 0) assert_greater_than(memory['free'], 0) assert_greater_than(memory['total'], 0) # assert_greater_than_or_equal() for locked in case locking pages failed at some point assert_greater_than_or_equal(memory['locked'], 0) assert_greater_than(memory['chunks_used'], 0) assert_greater_than(memory['chunks_free'], 0) assert_equal(memory['used'] + memory['free'], memory['total']) self.log.info("test mallocinfo") try: mallocinfo = node.getmemoryinfo(mode="mallocinfo") self.log.info('getmemoryinfo(mode="mallocinfo") call succeeded') tree = ET.fromstring(mallocinfo) assert_equal(tree.tag, 'malloc') except JSONRPCException: self.log.info('getmemoryinfo(mode="mallocinfo") not available') assert_raises_rpc_error(-8, 'mallocinfo is only available when compiled with glibc 2.10+', node.getmemoryinfo, mode="mallocinfo") assert_raises_rpc_error(-8, "unknown mode foobar", node.getmemoryinfo, mode="foobar") self.log.info("test logging rpc and help") # SYSCOIN Test logging RPC returns the expected number of logging categories. assert_equal(len(node.logging()), 36) # Test toggling a logging category on/off/on with the logging RPC. assert_equal(node.logging()['qt'], True) node.logging(exclude=['qt']) assert_equal(node.logging()['qt'], False) node.logging(include=['qt']) assert_equal(node.logging()['qt'], True) # Test logging RPC returns the logging categories in alphabetical order. sorted_logging_categories = sorted(node.logging()) assert_equal(list(node.logging()), sorted_logging_categories) # Test logging help returns the logging categories string in alphabetical order. categories = ', '.join(sorted_logging_categories) logging_help = self.nodes[0].help('logging') assert f"valid logging categories are: {categories}" in logging_help self.log.info("test echoipc (testing spawned process in multiprocess build)") assert_equal(node.echoipc("hello"), "hello") self.log.info("test getindexinfo") # Without any indices running the RPC returns an empty object assert_equal(node.getindexinfo(), {}) # Restart the node with indices and wait for them to sync self.restart_node(0, ["-txindex", "-blockfilterindex", "-coinstatsindex"]) self.wait_until(lambda: all(i["synced"] for i in node.getindexinfo().values())) # Returns a list of all running indices by default values = {"synced": True, "best_block_height": 200} assert_equal( node.getindexinfo(), { "txindex": values, "basic block filter index": values, "coinstatsindex": values, } ) # Specifying an index by name returns only the status of that index for i in {"txindex", "basic block filter index", "coinstatsindex"}:
# Specifying an unknown index name returns an empty result assert_equal(node.getindexinfo("foo"), {}) if __name__ == '__main__': RpcMiscTest().main()
assert_equal(node.getindexinfo(i), {i: values})
conditional_block
category-metadata.component.ts
import {MenuItem} from 'primeng/api'; import {ISubscription} from 'rxjs/Subscription'; import {SuggestionsProviderData} from '@kaltura-ng/kaltura-primeng-ui'; import {Subject} from 'rxjs'; import {Component, ElementRef, Inject, OnInit, QueryList, ViewChild, ViewChildren} from '@angular/core'; import {JumpToSection} from './jump-to-section.component'; import {DOCUMENT} from '@angular/common'; import {PageScrollInstance, PageScrollService} from 'ngx-page-scroll'; import {CategoryMetadataWidget} from './category-metadata-widget.service'; import { cancelOnDestroy, tag } from '@kaltura-ng/kaltura-common'; @Component({ selector: 'kmc-category-metadata', templateUrl: './category-metadata.component.html', styleUrls: ['./category-metadata.component.scss'] }) export class CategoryMetadataComponent implements OnInit { public _tagsProvider = new Subject<SuggestionsProviderData>(); private _searchTagsSubscription: ISubscription; private _popupStateChangeSubscribe: ISubscription; public _jumpToMenu: MenuItem[] = []; @ViewChildren(JumpToSection) private _jumpToSectionQuery: QueryList<JumpToSection> = null; @ViewChild('metadataContainer', { static: true }) public _container: ElementRef;
(public _widgetService: CategoryMetadataWidget, private _pageScrollService: PageScrollService, @Inject(DOCUMENT) private document: any) { } ngOnInit() { this._widgetService.attachForm(); } _searchTags(event): void { this._tagsProvider.next({ suggestions: [], isLoading: true }); if (this._searchTagsSubscription) { // abort previous request this._searchTagsSubscription.unsubscribe(); this._searchTagsSubscription = null; } this._searchTagsSubscription = this._widgetService.searchTags(event.query).subscribe(data => { const suggestions = []; const categoryTags = this._widgetService.metadataForm.value.tags || []; (data || []).forEach(suggestedTag => { const isSelectable = !categoryTags.find(tag => { return tag === suggestedTag; }); suggestions.push({ item: suggestedTag, isSelectable: isSelectable }); }); this._tagsProvider.next({ suggestions: suggestions, isLoading: false }); }, (err) => { this._tagsProvider.next({ suggestions: [], isLoading: false, errorMessage: <any>(err.message || err) }); }); } ngOnDestroy() { this._tagsProvider.complete(); this._searchTagsSubscription && this._searchTagsSubscription.unsubscribe(); this._popupStateChangeSubscribe && this._popupStateChangeSubscribe.unsubscribe(); this._widgetService.detachForm(); } ngAfterViewInit() { this._jumpToSectionQuery.changes .pipe(cancelOnDestroy(this)) .subscribe((query) => { this._updateJumpToSectionsMenu(); }); this._updateJumpToSectionsMenu(); } private _updateJumpToSectionsMenu() { const jumpToItems: any[] = []; this._jumpToSectionQuery.forEach(section => { const jumpToLabel = section.label; jumpToItems.push({ label: jumpToLabel, command: (event) => { this._jumpTo(section.htmlElement); } }); }); setTimeout(() => { this._jumpToMenu = jumpToItems; }); } private _jumpTo(element: HTMLElement) { let pageScrollInstance: PageScrollInstance = PageScrollInstance.newInstance({ document: this.document, scrollTarget: element, pageScrollOffset: 105 }); this._pageScrollService.start(pageScrollInstance); } }
constructor
identifier_name
category-metadata.component.ts
import {MenuItem} from 'primeng/api'; import {ISubscription} from 'rxjs/Subscription'; import {SuggestionsProviderData} from '@kaltura-ng/kaltura-primeng-ui'; import {Subject} from 'rxjs'; import {Component, ElementRef, Inject, OnInit, QueryList, ViewChild, ViewChildren} from '@angular/core'; import {JumpToSection} from './jump-to-section.component'; import {DOCUMENT} from '@angular/common'; import {PageScrollInstance, PageScrollService} from 'ngx-page-scroll'; import {CategoryMetadataWidget} from './category-metadata-widget.service'; import { cancelOnDestroy, tag } from '@kaltura-ng/kaltura-common'; @Component({ selector: 'kmc-category-metadata', templateUrl: './category-metadata.component.html', styleUrls: ['./category-metadata.component.scss'] }) export class CategoryMetadataComponent implements OnInit { public _tagsProvider = new Subject<SuggestionsProviderData>(); private _searchTagsSubscription: ISubscription; private _popupStateChangeSubscribe: ISubscription; public _jumpToMenu: MenuItem[] = []; @ViewChildren(JumpToSection) private _jumpToSectionQuery: QueryList<JumpToSection> = null; @ViewChild('metadataContainer', { static: true }) public _container: ElementRef; constructor(public _widgetService: CategoryMetadataWidget, private _pageScrollService: PageScrollService, @Inject(DOCUMENT) private document: any) { } ngOnInit() { this._widgetService.attachForm(); } _searchTags(event): void { this._tagsProvider.next({ suggestions: [], isLoading: true }); if (this._searchTagsSubscription)
this._searchTagsSubscription = this._widgetService.searchTags(event.query).subscribe(data => { const suggestions = []; const categoryTags = this._widgetService.metadataForm.value.tags || []; (data || []).forEach(suggestedTag => { const isSelectable = !categoryTags.find(tag => { return tag === suggestedTag; }); suggestions.push({ item: suggestedTag, isSelectable: isSelectable }); }); this._tagsProvider.next({ suggestions: suggestions, isLoading: false }); }, (err) => { this._tagsProvider.next({ suggestions: [], isLoading: false, errorMessage: <any>(err.message || err) }); }); } ngOnDestroy() { this._tagsProvider.complete(); this._searchTagsSubscription && this._searchTagsSubscription.unsubscribe(); this._popupStateChangeSubscribe && this._popupStateChangeSubscribe.unsubscribe(); this._widgetService.detachForm(); } ngAfterViewInit() { this._jumpToSectionQuery.changes .pipe(cancelOnDestroy(this)) .subscribe((query) => { this._updateJumpToSectionsMenu(); }); this._updateJumpToSectionsMenu(); } private _updateJumpToSectionsMenu() { const jumpToItems: any[] = []; this._jumpToSectionQuery.forEach(section => { const jumpToLabel = section.label; jumpToItems.push({ label: jumpToLabel, command: (event) => { this._jumpTo(section.htmlElement); } }); }); setTimeout(() => { this._jumpToMenu = jumpToItems; }); } private _jumpTo(element: HTMLElement) { let pageScrollInstance: PageScrollInstance = PageScrollInstance.newInstance({ document: this.document, scrollTarget: element, pageScrollOffset: 105 }); this._pageScrollService.start(pageScrollInstance); } }
{ // abort previous request this._searchTagsSubscription.unsubscribe(); this._searchTagsSubscription = null; }
conditional_block
category-metadata.component.ts
import {MenuItem} from 'primeng/api'; import {ISubscription} from 'rxjs/Subscription'; import {SuggestionsProviderData} from '@kaltura-ng/kaltura-primeng-ui'; import {Subject} from 'rxjs'; import {Component, ElementRef, Inject, OnInit, QueryList, ViewChild, ViewChildren} from '@angular/core'; import {JumpToSection} from './jump-to-section.component'; import {DOCUMENT} from '@angular/common'; import {PageScrollInstance, PageScrollService} from 'ngx-page-scroll'; import {CategoryMetadataWidget} from './category-metadata-widget.service'; import { cancelOnDestroy, tag } from '@kaltura-ng/kaltura-common'; @Component({ selector: 'kmc-category-metadata', templateUrl: './category-metadata.component.html', styleUrls: ['./category-metadata.component.scss'] }) export class CategoryMetadataComponent implements OnInit { public _tagsProvider = new Subject<SuggestionsProviderData>(); private _searchTagsSubscription: ISubscription; private _popupStateChangeSubscribe: ISubscription; public _jumpToMenu: MenuItem[] = []; @ViewChildren(JumpToSection) private _jumpToSectionQuery: QueryList<JumpToSection> = null; @ViewChild('metadataContainer', { static: true }) public _container: ElementRef; constructor(public _widgetService: CategoryMetadataWidget, private _pageScrollService: PageScrollService, @Inject(DOCUMENT) private document: any) { } ngOnInit() { this._widgetService.attachForm(); } _searchTags(event): void { this._tagsProvider.next({ suggestions: [], isLoading: true }); if (this._searchTagsSubscription) { // abort previous request this._searchTagsSubscription.unsubscribe(); this._searchTagsSubscription = null; } this._searchTagsSubscription = this._widgetService.searchTags(event.query).subscribe(data => { const suggestions = []; const categoryTags = this._widgetService.metadataForm.value.tags || []; (data || []).forEach(suggestedTag => { const isSelectable = !categoryTags.find(tag => { return tag === suggestedTag; }); suggestions.push({ item: suggestedTag, isSelectable: isSelectable }); }); this._tagsProvider.next({ suggestions: suggestions, isLoading: false }); }, (err) => { this._tagsProvider.next({ suggestions: [], isLoading: false, errorMessage: <any>(err.message || err) }); }); } ngOnDestroy() { this._tagsProvider.complete(); this._searchTagsSubscription && this._searchTagsSubscription.unsubscribe(); this._popupStateChangeSubscribe && this._popupStateChangeSubscribe.unsubscribe(); this._widgetService.detachForm(); } ngAfterViewInit() { this._jumpToSectionQuery.changes .pipe(cancelOnDestroy(this)) .subscribe((query) => { this._updateJumpToSectionsMenu(); }); this._updateJumpToSectionsMenu(); } private _updateJumpToSectionsMenu() { const jumpToItems: any[] = []; this._jumpToSectionQuery.forEach(section => { const jumpToLabel = section.label; jumpToItems.push({ label: jumpToLabel, command: (event) => { this._jumpTo(section.htmlElement); } }); }); setTimeout(() => { this._jumpToMenu = jumpToItems; }); } private _jumpTo(element: HTMLElement)
}
{ let pageScrollInstance: PageScrollInstance = PageScrollInstance.newInstance({ document: this.document, scrollTarget: element, pageScrollOffset: 105 }); this._pageScrollService.start(pageScrollInstance); }
identifier_body
category-metadata.component.ts
import {MenuItem} from 'primeng/api'; import {ISubscription} from 'rxjs/Subscription'; import {SuggestionsProviderData} from '@kaltura-ng/kaltura-primeng-ui'; import {Subject} from 'rxjs'; import {Component, ElementRef, Inject, OnInit, QueryList, ViewChild, ViewChildren} from '@angular/core'; import {JumpToSection} from './jump-to-section.component'; import {DOCUMENT} from '@angular/common'; import {PageScrollInstance, PageScrollService} from 'ngx-page-scroll'; import {CategoryMetadataWidget} from './category-metadata-widget.service'; import { cancelOnDestroy, tag } from '@kaltura-ng/kaltura-common'; @Component({ selector: 'kmc-category-metadata', templateUrl: './category-metadata.component.html', styleUrls: ['./category-metadata.component.scss'] }) export class CategoryMetadataComponent implements OnInit {
private _popupStateChangeSubscribe: ISubscription; public _jumpToMenu: MenuItem[] = []; @ViewChildren(JumpToSection) private _jumpToSectionQuery: QueryList<JumpToSection> = null; @ViewChild('metadataContainer', { static: true }) public _container: ElementRef; constructor(public _widgetService: CategoryMetadataWidget, private _pageScrollService: PageScrollService, @Inject(DOCUMENT) private document: any) { } ngOnInit() { this._widgetService.attachForm(); } _searchTags(event): void { this._tagsProvider.next({ suggestions: [], isLoading: true }); if (this._searchTagsSubscription) { // abort previous request this._searchTagsSubscription.unsubscribe(); this._searchTagsSubscription = null; } this._searchTagsSubscription = this._widgetService.searchTags(event.query).subscribe(data => { const suggestions = []; const categoryTags = this._widgetService.metadataForm.value.tags || []; (data || []).forEach(suggestedTag => { const isSelectable = !categoryTags.find(tag => { return tag === suggestedTag; }); suggestions.push({ item: suggestedTag, isSelectable: isSelectable }); }); this._tagsProvider.next({ suggestions: suggestions, isLoading: false }); }, (err) => { this._tagsProvider.next({ suggestions: [], isLoading: false, errorMessage: <any>(err.message || err) }); }); } ngOnDestroy() { this._tagsProvider.complete(); this._searchTagsSubscription && this._searchTagsSubscription.unsubscribe(); this._popupStateChangeSubscribe && this._popupStateChangeSubscribe.unsubscribe(); this._widgetService.detachForm(); } ngAfterViewInit() { this._jumpToSectionQuery.changes .pipe(cancelOnDestroy(this)) .subscribe((query) => { this._updateJumpToSectionsMenu(); }); this._updateJumpToSectionsMenu(); } private _updateJumpToSectionsMenu() { const jumpToItems: any[] = []; this._jumpToSectionQuery.forEach(section => { const jumpToLabel = section.label; jumpToItems.push({ label: jumpToLabel, command: (event) => { this._jumpTo(section.htmlElement); } }); }); setTimeout(() => { this._jumpToMenu = jumpToItems; }); } private _jumpTo(element: HTMLElement) { let pageScrollInstance: PageScrollInstance = PageScrollInstance.newInstance({ document: this.document, scrollTarget: element, pageScrollOffset: 105 }); this._pageScrollService.start(pageScrollInstance); } }
public _tagsProvider = new Subject<SuggestionsProviderData>(); private _searchTagsSubscription: ISubscription;
random_line_split
sprites.rs
use sdl2::rect::Rect; use sdl2::video::Window; use sdl2::render::{Texture, Canvas}; pub struct Sprite<'a> { rect: Rect, pub size: Rect, texture: &'a Texture, } impl<'a> Sprite<'a> { pub fn
(&self, x: i32, y: i32, canvas: &mut Canvas<Window>) { let pos_rect = Rect::new(x, y, self.size.width(), self.size.height()); match canvas.copy(&self.texture, Some(self.rect), Some(pos_rect)) { Err(e) => println!("canvas copy error: {}", e), _ => {} } } } pub struct SpriteSheet { pub sprite_width: u32, pub sprite_height: u32, padding: u32, pub texture: Texture, } impl SpriteSheet { pub fn new(texture: Texture, sprite_width: u32, sprite_height: u32, padding: u32) -> Self { SpriteSheet { sprite_width, sprite_height, padding, texture: texture, } } // Creates a sprite object pub fn get_sprite(&self, index: usize) -> Sprite { let texture_query = self.texture.query(); let sheet_width = texture_query.width; let columns = sheet_width / (self.sprite_width + self.padding); let sheet_x = index as u32 % columns; let sheet_y = index as u32 / columns; let px = sheet_x * (self.sprite_width + self.padding); let py = sheet_y * (self.sprite_height + self.padding); Sprite { rect: Rect::new(px as i32, py as i32, self.sprite_width, self.sprite_height), size: Rect::new(0, 0, self.sprite_width, self.sprite_height), texture: &self.texture, } } }
draw
identifier_name
sprites.rs
use sdl2::rect::Rect; use sdl2::video::Window; use sdl2::render::{Texture, Canvas}; pub struct Sprite<'a> { rect: Rect, pub size: Rect, texture: &'a Texture, } impl<'a> Sprite<'a> { pub fn draw(&self, x: i32, y: i32, canvas: &mut Canvas<Window>) { let pos_rect = Rect::new(x, y, self.size.width(), self.size.height()); match canvas.copy(&self.texture, Some(self.rect), Some(pos_rect)) { Err(e) => println!("canvas copy error: {}", e), _ =>
} } } pub struct SpriteSheet { pub sprite_width: u32, pub sprite_height: u32, padding: u32, pub texture: Texture, } impl SpriteSheet { pub fn new(texture: Texture, sprite_width: u32, sprite_height: u32, padding: u32) -> Self { SpriteSheet { sprite_width, sprite_height, padding, texture: texture, } } // Creates a sprite object pub fn get_sprite(&self, index: usize) -> Sprite { let texture_query = self.texture.query(); let sheet_width = texture_query.width; let columns = sheet_width / (self.sprite_width + self.padding); let sheet_x = index as u32 % columns; let sheet_y = index as u32 / columns; let px = sheet_x * (self.sprite_width + self.padding); let py = sheet_y * (self.sprite_height + self.padding); Sprite { rect: Rect::new(px as i32, py as i32, self.sprite_width, self.sprite_height), size: Rect::new(0, 0, self.sprite_width, self.sprite_height), texture: &self.texture, } } }
{}
conditional_block
sprites.rs
use sdl2::rect::Rect; use sdl2::video::Window; use sdl2::render::{Texture, Canvas}; pub struct Sprite<'a> { rect: Rect, pub size: Rect, texture: &'a Texture, } impl<'a> Sprite<'a> { pub fn draw(&self, x: i32, y: i32, canvas: &mut Canvas<Window>) { let pos_rect = Rect::new(x, y, self.size.width(), self.size.height()); match canvas.copy(&self.texture, Some(self.rect), Some(pos_rect)) { Err(e) => println!("canvas copy error: {}", e), _ => {} } } } pub struct SpriteSheet { pub sprite_width: u32, pub sprite_height: u32, padding: u32, pub texture: Texture, } impl SpriteSheet { pub fn new(texture: Texture, sprite_width: u32, sprite_height: u32, padding: u32) -> Self { SpriteSheet { sprite_width,
} // Creates a sprite object pub fn get_sprite(&self, index: usize) -> Sprite { let texture_query = self.texture.query(); let sheet_width = texture_query.width; let columns = sheet_width / (self.sprite_width + self.padding); let sheet_x = index as u32 % columns; let sheet_y = index as u32 / columns; let px = sheet_x * (self.sprite_width + self.padding); let py = sheet_y * (self.sprite_height + self.padding); Sprite { rect: Rect::new(px as i32, py as i32, self.sprite_width, self.sprite_height), size: Rect::new(0, 0, self.sprite_width, self.sprite_height), texture: &self.texture, } } }
sprite_height, padding, texture: texture, }
random_line_split
sprites.rs
use sdl2::rect::Rect; use sdl2::video::Window; use sdl2::render::{Texture, Canvas}; pub struct Sprite<'a> { rect: Rect, pub size: Rect, texture: &'a Texture, } impl<'a> Sprite<'a> { pub fn draw(&self, x: i32, y: i32, canvas: &mut Canvas<Window>)
} pub struct SpriteSheet { pub sprite_width: u32, pub sprite_height: u32, padding: u32, pub texture: Texture, } impl SpriteSheet { pub fn new(texture: Texture, sprite_width: u32, sprite_height: u32, padding: u32) -> Self { SpriteSheet { sprite_width, sprite_height, padding, texture: texture, } } // Creates a sprite object pub fn get_sprite(&self, index: usize) -> Sprite { let texture_query = self.texture.query(); let sheet_width = texture_query.width; let columns = sheet_width / (self.sprite_width + self.padding); let sheet_x = index as u32 % columns; let sheet_y = index as u32 / columns; let px = sheet_x * (self.sprite_width + self.padding); let py = sheet_y * (self.sprite_height + self.padding); Sprite { rect: Rect::new(px as i32, py as i32, self.sprite_width, self.sprite_height), size: Rect::new(0, 0, self.sprite_width, self.sprite_height), texture: &self.texture, } } }
{ let pos_rect = Rect::new(x, y, self.size.width(), self.size.height()); match canvas.copy(&self.texture, Some(self.rect), Some(pos_rect)) { Err(e) => println!("canvas copy error: {}", e), _ => {} } }
identifier_body
motion.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Generic types for CSS Motion Path. use crate::values::specified::SVGPathData; /// The <size> in ray() function. /// /// https://drafts.fxtf.org/motion-1/#valdef-offsetpath-size #[allow(missing_docs)] #[derive( Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] #[repr(u8)] pub enum
{ ClosestSide, ClosestCorner, FarthestSide, FarthestCorner, Sides, } /// The `ray()` function, `ray( [ <angle> && <size> && contain? ] )` /// /// https://drafts.fxtf.org/motion-1/#valdef-offsetpath-ray #[derive( Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] #[repr(C)] pub struct RayFunction<Angle> { /// The bearing angle with `0deg` pointing up and positive angles /// representing clockwise rotation. pub angle: Angle, /// Decide the path length used when `offset-distance` is expressed /// as a percentage. #[animation(constant)] pub size: RaySize, /// Clamp `offset-distance` so that the box is entirely contained /// within the path. #[animation(constant)] #[css(represents_keyword)] pub contain: bool, } /// The offset-path value. /// /// https://drafts.fxtf.org/motion-1/#offset-path-property #[derive( Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] #[repr(C, u8)] pub enum GenericOffsetPath<Angle> { // We could merge SVGPathData into ShapeSource, so we could reuse them. However, // we don't want to support other value for offset-path, so use SVGPathData only for now. /// Path value for path(<string>). #[css(function)] Path(SVGPathData), /// ray() function, which defines a path in the polar coordinate system. #[css(function)] Ray(RayFunction<Angle>), /// None value. #[animation(error)] None, // Bug 1186329: Implement <basic-shape>, <geometry-box>, and <url>. } pub use self::GenericOffsetPath as OffsetPath; impl<Angle> OffsetPath<Angle> { /// Return None. #[inline] pub fn none() -> Self { OffsetPath::None } }
RaySize
identifier_name
motion.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Generic types for CSS Motion Path. use crate::values::specified::SVGPathData; /// The <size> in ray() function. /// /// https://drafts.fxtf.org/motion-1/#valdef-offsetpath-size #[allow(missing_docs)] #[derive( Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] #[repr(u8)] pub enum RaySize { ClosestSide, ClosestCorner, FarthestSide, FarthestCorner, Sides, } /// The `ray()` function, `ray( [ <angle> && <size> && contain? ] )` /// /// https://drafts.fxtf.org/motion-1/#valdef-offsetpath-ray #[derive( Animate, Clone, ComputeSquaredDistance, Debug,
ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] #[repr(C)] pub struct RayFunction<Angle> { /// The bearing angle with `0deg` pointing up and positive angles /// representing clockwise rotation. pub angle: Angle, /// Decide the path length used when `offset-distance` is expressed /// as a percentage. #[animation(constant)] pub size: RaySize, /// Clamp `offset-distance` so that the box is entirely contained /// within the path. #[animation(constant)] #[css(represents_keyword)] pub contain: bool, } /// The offset-path value. /// /// https://drafts.fxtf.org/motion-1/#offset-path-property #[derive( Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] #[repr(C, u8)] pub enum GenericOffsetPath<Angle> { // We could merge SVGPathData into ShapeSource, so we could reuse them. However, // we don't want to support other value for offset-path, so use SVGPathData only for now. /// Path value for path(<string>). #[css(function)] Path(SVGPathData), /// ray() function, which defines a path in the polar coordinate system. #[css(function)] Ray(RayFunction<Angle>), /// None value. #[animation(error)] None, // Bug 1186329: Implement <basic-shape>, <geometry-box>, and <url>. } pub use self::GenericOffsetPath as OffsetPath; impl<Angle> OffsetPath<Angle> { /// Return None. #[inline] pub fn none() -> Self { OffsetPath::None } }
MallocSizeOf, PartialEq, SpecifiedValueInfo,
random_line_split
config-store.es5.js
/** @license * @pnp/config-store v1.1.3 - pnp - provides a way to manage configuration within your application * MIT (https://github.com/pnp/pnpjs/blob/master/LICENSE) * Copyright (c) 2018 Microsoft * docs: https://pnp.github.io/pnpjs/ * source: https:github.com/pnp/pnpjs * bugs: https://github.com/pnp/pnpjs/issues */ import { Dictionary, PnPClientStorage } from '@pnp/common'; import { __extends } from 'tslib'; import { Logger } from '@pnp/logging'; /** * Class used to manage the current application settings * */ var Settings = /** @class */ (function () { /** * Creates a new instance of the settings class * * @constructor */ function Settings() { this._settings = new Dictionary(); } /** * Adds a new single setting, or overwrites a previous setting with the same key * * @param {string} key The key used to store this setting * @param {string} value The setting value to store */ Settings.prototype.add = function (key, value) { this._settings.add(key, value); }; /** * Adds a JSON value to the collection as a string, you must use getJSON to rehydrate the object when read * * @param {string} key The key used to store this setting * @param {any} value The setting value to store */ Settings.prototype.addJSON = function (key, value) { this._settings.add(key, JSON.stringify(value)); }; /** * Applies the supplied hash to the setting collection overwriting any existing value, or created new values * * @param {TypedHash<any>} hash The set of values to add */ Settings.prototype.apply = function (hash) { var _this = this; return new Promise(function (resolve, reject) { try { _this._settings.merge(hash); resolve(); } catch (e) { reject(e); } }); }; /** * Loads configuration settings into the collection from the supplied provider and returns a Promise * * @param {IConfigurationProvider} provider The provider from which we will load the settings */ Settings.prototype.load = function (provider) { var _this = this; return new Promise(function (resolve, reject) { provider.getConfiguration().then(function (value) { _this._settings.merge(value); resolve(); }).catch(reject); }); }; /** * Gets a value from the configuration * * @param {string} key The key whose value we want to return. Returns null if the key does not exist * @return {string} string value from the configuration */ Settings.prototype.get = function (key) { return this._settings.get(key); }; /** * Gets a JSON value, rehydrating the stored string to the original object * * @param {string} key The key whose value we want to return. Returns null if the key does not exist * @return {any} object from the configuration */ Settings.prototype.getJSON = function (key) { var o = this.get(key); if (typeof o === "undefined" || o === null) { return o; } return JSON.parse(o); }; return Settings; }()); var NoCacheAvailableException = /** @class */ (function (_super) { __extends(NoCacheAvailableException, _super); function NoCacheAvailableException(msg) { if (msg === void 0) { msg = "Cannot create a caching configuration provider since cache is not available."; } var _this = _super.call(this, msg) || this; _this.name = "NoCacheAvailableException"; Logger.log({ data: {}, level: 3 /* Error */, message: "[" + _this.name + "]::" + _this.message }); return _this; } return NoCacheAvailableException; }(Error)); /** * A caching provider which can wrap other non-caching providers * */ var CachingConfigurationProvider = /** @class */ (function () { /** * Creates a new caching configuration provider * @constructor * @param {IConfigurationProvider} wrappedProvider Provider which will be used to fetch the configuration * @param {string} cacheKey Key that will be used to store cached items to the cache * @param {IPnPClientStore} cacheStore OPTIONAL storage, which will be used to store cached settings. */ function CachingConfigurationProvider(wrappedProvider, cacheKey, cacheStore) { this.wrappedProvider = wrappedProvider; this.cacheKey = cacheKey; this.wrappedProvider = wrappedProvider; this.store = (cacheStore) ? cacheStore : this.selectPnPCache(); } /** * Gets the wrapped configuration providers * * @return {IConfigurationProvider} Wrapped configuration provider */ CachingConfigurationProvider.prototype.getWrappedProvider = function () { return this.wrappedProvider; }; /**
*/ CachingConfigurationProvider.prototype.getConfiguration = function () { var _this = this; // Cache not available, pass control to the wrapped provider if ((!this.store) || (!this.store.enabled)) { return this.wrappedProvider.getConfiguration(); } return this.store.getOrPut(this.cacheKey, function () { return _this.wrappedProvider.getConfiguration().then(function (providedConfig) { _this.store.put(_this.cacheKey, providedConfig); return providedConfig; }); }); }; CachingConfigurationProvider.prototype.selectPnPCache = function () { var pnpCache = new PnPClientStorage(); if ((pnpCache.local) && (pnpCache.local.enabled)) { return pnpCache.local; } if ((pnpCache.session) && (pnpCache.session.enabled)) { return pnpCache.session; } throw new NoCacheAvailableException(); }; return CachingConfigurationProvider; }()); /** * A configuration provider which loads configuration values from a SharePoint list * */ var SPListConfigurationProvider = /** @class */ (function () { /** * Creates a new SharePoint list based configuration provider * @constructor * @param {string} webUrl Url of the SharePoint site, where the configuration list is located * @param {string} listTitle Title of the SharePoint list, which contains the configuration settings (optional, default: "config") * @param {string} keyFieldName The name of the field in the list to use as the setting key (optional, default: "Title") * @param {string} valueFieldName The name of the field in the list to use as the setting value (optional, default: "Value") */ function SPListConfigurationProvider(web, listTitle, keyFieldName, valueFieldName) { if (listTitle === void 0) { listTitle = "config"; } if (keyFieldName === void 0) { keyFieldName = "Title"; } if (valueFieldName === void 0) { valueFieldName = "Value"; } this.web = web; this.listTitle = listTitle; this.keyFieldName = keyFieldName; this.valueFieldName = valueFieldName; } /** * Loads the configuration values from the SharePoint list * * @return {Promise<TypedHash<string>>} Promise of loaded configuration values */ SPListConfigurationProvider.prototype.getConfiguration = function () { var _this = this; return this.web.lists.getByTitle(this.listTitle).items.select(this.keyFieldName, this.valueFieldName).get() .then(function (data) { return data.reduce(function (c, item) { c[item[_this.keyFieldName]] = item[_this.valueFieldName]; return c; }, {}); }); }; /** * Wraps the current provider in a cache enabled provider * * @return {CachingConfigurationProvider} Caching providers which wraps the current provider */ SPListConfigurationProvider.prototype.asCaching = function (cacheKey) { if (cacheKey === void 0) { cacheKey = "pnp_configcache_splist_" + this.web.toUrl() + "+" + this.listTitle; } return new CachingConfigurationProvider(this, cacheKey); }; return SPListConfigurationProvider; }()); export { Settings, CachingConfigurationProvider, SPListConfigurationProvider, NoCacheAvailableException }; //# sourceMappingURL=config-store.es5.js.map
* Loads the configuration values either from the cache or from the wrapped provider * * @return {Promise<TypedHash<string>>} Promise of loaded configuration values
random_line_split
config-store.es5.js
/** @license * @pnp/config-store v1.1.3 - pnp - provides a way to manage configuration within your application * MIT (https://github.com/pnp/pnpjs/blob/master/LICENSE) * Copyright (c) 2018 Microsoft * docs: https://pnp.github.io/pnpjs/ * source: https:github.com/pnp/pnpjs * bugs: https://github.com/pnp/pnpjs/issues */ import { Dictionary, PnPClientStorage } from '@pnp/common'; import { __extends } from 'tslib'; import { Logger } from '@pnp/logging'; /** * Class used to manage the current application settings * */ var Settings = /** @class */ (function () { /** * Creates a new instance of the settings class * * @constructor */ function Settings() { this._settings = new Dictionary(); } /** * Adds a new single setting, or overwrites a previous setting with the same key * * @param {string} key The key used to store this setting * @param {string} value The setting value to store */ Settings.prototype.add = function (key, value) { this._settings.add(key, value); }; /** * Adds a JSON value to the collection as a string, you must use getJSON to rehydrate the object when read * * @param {string} key The key used to store this setting * @param {any} value The setting value to store */ Settings.prototype.addJSON = function (key, value) { this._settings.add(key, JSON.stringify(value)); }; /** * Applies the supplied hash to the setting collection overwriting any existing value, or created new values * * @param {TypedHash<any>} hash The set of values to add */ Settings.prototype.apply = function (hash) { var _this = this; return new Promise(function (resolve, reject) { try { _this._settings.merge(hash); resolve(); } catch (e) { reject(e); } }); }; /** * Loads configuration settings into the collection from the supplied provider and returns a Promise * * @param {IConfigurationProvider} provider The provider from which we will load the settings */ Settings.prototype.load = function (provider) { var _this = this; return new Promise(function (resolve, reject) { provider.getConfiguration().then(function (value) { _this._settings.merge(value); resolve(); }).catch(reject); }); }; /** * Gets a value from the configuration * * @param {string} key The key whose value we want to return. Returns null if the key does not exist * @return {string} string value from the configuration */ Settings.prototype.get = function (key) { return this._settings.get(key); }; /** * Gets a JSON value, rehydrating the stored string to the original object * * @param {string} key The key whose value we want to return. Returns null if the key does not exist * @return {any} object from the configuration */ Settings.prototype.getJSON = function (key) { var o = this.get(key); if (typeof o === "undefined" || o === null) { return o; } return JSON.parse(o); }; return Settings; }()); var NoCacheAvailableException = /** @class */ (function (_super) { __extends(NoCacheAvailableException, _super); function NoCacheAvailableException(msg) { if (msg === void 0) { msg = "Cannot create a caching configuration provider since cache is not available."; } var _this = _super.call(this, msg) || this; _this.name = "NoCacheAvailableException"; Logger.log({ data: {}, level: 3 /* Error */, message: "[" + _this.name + "]::" + _this.message }); return _this; } return NoCacheAvailableException; }(Error)); /** * A caching provider which can wrap other non-caching providers * */ var CachingConfigurationProvider = /** @class */ (function () { /** * Creates a new caching configuration provider * @constructor * @param {IConfigurationProvider} wrappedProvider Provider which will be used to fetch the configuration * @param {string} cacheKey Key that will be used to store cached items to the cache * @param {IPnPClientStore} cacheStore OPTIONAL storage, which will be used to store cached settings. */ function CachingConfigurationProvider(wrappedProvider, cacheKey, cacheStore) { this.wrappedProvider = wrappedProvider; this.cacheKey = cacheKey; this.wrappedProvider = wrappedProvider; this.store = (cacheStore) ? cacheStore : this.selectPnPCache(); } /** * Gets the wrapped configuration providers * * @return {IConfigurationProvider} Wrapped configuration provider */ CachingConfigurationProvider.prototype.getWrappedProvider = function () { return this.wrappedProvider; }; /** * Loads the configuration values either from the cache or from the wrapped provider * * @return {Promise<TypedHash<string>>} Promise of loaded configuration values */ CachingConfigurationProvider.prototype.getConfiguration = function () { var _this = this; // Cache not available, pass control to the wrapped provider if ((!this.store) || (!this.store.enabled)) { return this.wrappedProvider.getConfiguration(); } return this.store.getOrPut(this.cacheKey, function () { return _this.wrappedProvider.getConfiguration().then(function (providedConfig) { _this.store.put(_this.cacheKey, providedConfig); return providedConfig; }); }); }; CachingConfigurationProvider.prototype.selectPnPCache = function () { var pnpCache = new PnPClientStorage(); if ((pnpCache.local) && (pnpCache.local.enabled)) { return pnpCache.local; } if ((pnpCache.session) && (pnpCache.session.enabled)) { return pnpCache.session; } throw new NoCacheAvailableException(); }; return CachingConfigurationProvider; }()); /** * A configuration provider which loads configuration values from a SharePoint list * */ var SPListConfigurationProvider = /** @class */ (function () { /** * Creates a new SharePoint list based configuration provider * @constructor * @param {string} webUrl Url of the SharePoint site, where the configuration list is located * @param {string} listTitle Title of the SharePoint list, which contains the configuration settings (optional, default: "config") * @param {string} keyFieldName The name of the field in the list to use as the setting key (optional, default: "Title") * @param {string} valueFieldName The name of the field in the list to use as the setting value (optional, default: "Value") */ function
(web, listTitle, keyFieldName, valueFieldName) { if (listTitle === void 0) { listTitle = "config"; } if (keyFieldName === void 0) { keyFieldName = "Title"; } if (valueFieldName === void 0) { valueFieldName = "Value"; } this.web = web; this.listTitle = listTitle; this.keyFieldName = keyFieldName; this.valueFieldName = valueFieldName; } /** * Loads the configuration values from the SharePoint list * * @return {Promise<TypedHash<string>>} Promise of loaded configuration values */ SPListConfigurationProvider.prototype.getConfiguration = function () { var _this = this; return this.web.lists.getByTitle(this.listTitle).items.select(this.keyFieldName, this.valueFieldName).get() .then(function (data) { return data.reduce(function (c, item) { c[item[_this.keyFieldName]] = item[_this.valueFieldName]; return c; }, {}); }); }; /** * Wraps the current provider in a cache enabled provider * * @return {CachingConfigurationProvider} Caching providers which wraps the current provider */ SPListConfigurationProvider.prototype.asCaching = function (cacheKey) { if (cacheKey === void 0) { cacheKey = "pnp_configcache_splist_" + this.web.toUrl() + "+" + this.listTitle; } return new CachingConfigurationProvider(this, cacheKey); }; return SPListConfigurationProvider; }()); export { Settings, CachingConfigurationProvider, SPListConfigurationProvider, NoCacheAvailableException }; //# sourceMappingURL=config-store.es5.js.map
SPListConfigurationProvider
identifier_name
config-store.es5.js
/** @license * @pnp/config-store v1.1.3 - pnp - provides a way to manage configuration within your application * MIT (https://github.com/pnp/pnpjs/blob/master/LICENSE) * Copyright (c) 2018 Microsoft * docs: https://pnp.github.io/pnpjs/ * source: https:github.com/pnp/pnpjs * bugs: https://github.com/pnp/pnpjs/issues */ import { Dictionary, PnPClientStorage } from '@pnp/common'; import { __extends } from 'tslib'; import { Logger } from '@pnp/logging'; /** * Class used to manage the current application settings * */ var Settings = /** @class */ (function () { /** * Creates a new instance of the settings class * * @constructor */ function Settings() { this._settings = new Dictionary(); } /** * Adds a new single setting, or overwrites a previous setting with the same key * * @param {string} key The key used to store this setting * @param {string} value The setting value to store */ Settings.prototype.add = function (key, value) { this._settings.add(key, value); }; /** * Adds a JSON value to the collection as a string, you must use getJSON to rehydrate the object when read * * @param {string} key The key used to store this setting * @param {any} value The setting value to store */ Settings.prototype.addJSON = function (key, value) { this._settings.add(key, JSON.stringify(value)); }; /** * Applies the supplied hash to the setting collection overwriting any existing value, or created new values * * @param {TypedHash<any>} hash The set of values to add */ Settings.prototype.apply = function (hash) { var _this = this; return new Promise(function (resolve, reject) { try { _this._settings.merge(hash); resolve(); } catch (e) { reject(e); } }); }; /** * Loads configuration settings into the collection from the supplied provider and returns a Promise * * @param {IConfigurationProvider} provider The provider from which we will load the settings */ Settings.prototype.load = function (provider) { var _this = this; return new Promise(function (resolve, reject) { provider.getConfiguration().then(function (value) { _this._settings.merge(value); resolve(); }).catch(reject); }); }; /** * Gets a value from the configuration * * @param {string} key The key whose value we want to return. Returns null if the key does not exist * @return {string} string value from the configuration */ Settings.prototype.get = function (key) { return this._settings.get(key); }; /** * Gets a JSON value, rehydrating the stored string to the original object * * @param {string} key The key whose value we want to return. Returns null if the key does not exist * @return {any} object from the configuration */ Settings.prototype.getJSON = function (key) { var o = this.get(key); if (typeof o === "undefined" || o === null) { return o; } return JSON.parse(o); }; return Settings; }()); var NoCacheAvailableException = /** @class */ (function (_super) { __extends(NoCacheAvailableException, _super); function NoCacheAvailableException(msg)
return NoCacheAvailableException; }(Error)); /** * A caching provider which can wrap other non-caching providers * */ var CachingConfigurationProvider = /** @class */ (function () { /** * Creates a new caching configuration provider * @constructor * @param {IConfigurationProvider} wrappedProvider Provider which will be used to fetch the configuration * @param {string} cacheKey Key that will be used to store cached items to the cache * @param {IPnPClientStore} cacheStore OPTIONAL storage, which will be used to store cached settings. */ function CachingConfigurationProvider(wrappedProvider, cacheKey, cacheStore) { this.wrappedProvider = wrappedProvider; this.cacheKey = cacheKey; this.wrappedProvider = wrappedProvider; this.store = (cacheStore) ? cacheStore : this.selectPnPCache(); } /** * Gets the wrapped configuration providers * * @return {IConfigurationProvider} Wrapped configuration provider */ CachingConfigurationProvider.prototype.getWrappedProvider = function () { return this.wrappedProvider; }; /** * Loads the configuration values either from the cache or from the wrapped provider * * @return {Promise<TypedHash<string>>} Promise of loaded configuration values */ CachingConfigurationProvider.prototype.getConfiguration = function () { var _this = this; // Cache not available, pass control to the wrapped provider if ((!this.store) || (!this.store.enabled)) { return this.wrappedProvider.getConfiguration(); } return this.store.getOrPut(this.cacheKey, function () { return _this.wrappedProvider.getConfiguration().then(function (providedConfig) { _this.store.put(_this.cacheKey, providedConfig); return providedConfig; }); }); }; CachingConfigurationProvider.prototype.selectPnPCache = function () { var pnpCache = new PnPClientStorage(); if ((pnpCache.local) && (pnpCache.local.enabled)) { return pnpCache.local; } if ((pnpCache.session) && (pnpCache.session.enabled)) { return pnpCache.session; } throw new NoCacheAvailableException(); }; return CachingConfigurationProvider; }()); /** * A configuration provider which loads configuration values from a SharePoint list * */ var SPListConfigurationProvider = /** @class */ (function () { /** * Creates a new SharePoint list based configuration provider * @constructor * @param {string} webUrl Url of the SharePoint site, where the configuration list is located * @param {string} listTitle Title of the SharePoint list, which contains the configuration settings (optional, default: "config") * @param {string} keyFieldName The name of the field in the list to use as the setting key (optional, default: "Title") * @param {string} valueFieldName The name of the field in the list to use as the setting value (optional, default: "Value") */ function SPListConfigurationProvider(web, listTitle, keyFieldName, valueFieldName) { if (listTitle === void 0) { listTitle = "config"; } if (keyFieldName === void 0) { keyFieldName = "Title"; } if (valueFieldName === void 0) { valueFieldName = "Value"; } this.web = web; this.listTitle = listTitle; this.keyFieldName = keyFieldName; this.valueFieldName = valueFieldName; } /** * Loads the configuration values from the SharePoint list * * @return {Promise<TypedHash<string>>} Promise of loaded configuration values */ SPListConfigurationProvider.prototype.getConfiguration = function () { var _this = this; return this.web.lists.getByTitle(this.listTitle).items.select(this.keyFieldName, this.valueFieldName).get() .then(function (data) { return data.reduce(function (c, item) { c[item[_this.keyFieldName]] = item[_this.valueFieldName]; return c; }, {}); }); }; /** * Wraps the current provider in a cache enabled provider * * @return {CachingConfigurationProvider} Caching providers which wraps the current provider */ SPListConfigurationProvider.prototype.asCaching = function (cacheKey) { if (cacheKey === void 0) { cacheKey = "pnp_configcache_splist_" + this.web.toUrl() + "+" + this.listTitle; } return new CachingConfigurationProvider(this, cacheKey); }; return SPListConfigurationProvider; }()); export { Settings, CachingConfigurationProvider, SPListConfigurationProvider, NoCacheAvailableException }; //# sourceMappingURL=config-store.es5.js.map
{ if (msg === void 0) { msg = "Cannot create a caching configuration provider since cache is not available."; } var _this = _super.call(this, msg) || this; _this.name = "NoCacheAvailableException"; Logger.log({ data: {}, level: 3 /* Error */, message: "[" + _this.name + "]::" + _this.message }); return _this; }
identifier_body
config-store.es5.js
/** @license * @pnp/config-store v1.1.3 - pnp - provides a way to manage configuration within your application * MIT (https://github.com/pnp/pnpjs/blob/master/LICENSE) * Copyright (c) 2018 Microsoft * docs: https://pnp.github.io/pnpjs/ * source: https:github.com/pnp/pnpjs * bugs: https://github.com/pnp/pnpjs/issues */ import { Dictionary, PnPClientStorage } from '@pnp/common'; import { __extends } from 'tslib'; import { Logger } from '@pnp/logging'; /** * Class used to manage the current application settings * */ var Settings = /** @class */ (function () { /** * Creates a new instance of the settings class * * @constructor */ function Settings() { this._settings = new Dictionary(); } /** * Adds a new single setting, or overwrites a previous setting with the same key * * @param {string} key The key used to store this setting * @param {string} value The setting value to store */ Settings.prototype.add = function (key, value) { this._settings.add(key, value); }; /** * Adds a JSON value to the collection as a string, you must use getJSON to rehydrate the object when read * * @param {string} key The key used to store this setting * @param {any} value The setting value to store */ Settings.prototype.addJSON = function (key, value) { this._settings.add(key, JSON.stringify(value)); }; /** * Applies the supplied hash to the setting collection overwriting any existing value, or created new values * * @param {TypedHash<any>} hash The set of values to add */ Settings.prototype.apply = function (hash) { var _this = this; return new Promise(function (resolve, reject) { try { _this._settings.merge(hash); resolve(); } catch (e) { reject(e); } }); }; /** * Loads configuration settings into the collection from the supplied provider and returns a Promise * * @param {IConfigurationProvider} provider The provider from which we will load the settings */ Settings.prototype.load = function (provider) { var _this = this; return new Promise(function (resolve, reject) { provider.getConfiguration().then(function (value) { _this._settings.merge(value); resolve(); }).catch(reject); }); }; /** * Gets a value from the configuration * * @param {string} key The key whose value we want to return. Returns null if the key does not exist * @return {string} string value from the configuration */ Settings.prototype.get = function (key) { return this._settings.get(key); }; /** * Gets a JSON value, rehydrating the stored string to the original object * * @param {string} key The key whose value we want to return. Returns null if the key does not exist * @return {any} object from the configuration */ Settings.prototype.getJSON = function (key) { var o = this.get(key); if (typeof o === "undefined" || o === null)
return JSON.parse(o); }; return Settings; }()); var NoCacheAvailableException = /** @class */ (function (_super) { __extends(NoCacheAvailableException, _super); function NoCacheAvailableException(msg) { if (msg === void 0) { msg = "Cannot create a caching configuration provider since cache is not available."; } var _this = _super.call(this, msg) || this; _this.name = "NoCacheAvailableException"; Logger.log({ data: {}, level: 3 /* Error */, message: "[" + _this.name + "]::" + _this.message }); return _this; } return NoCacheAvailableException; }(Error)); /** * A caching provider which can wrap other non-caching providers * */ var CachingConfigurationProvider = /** @class */ (function () { /** * Creates a new caching configuration provider * @constructor * @param {IConfigurationProvider} wrappedProvider Provider which will be used to fetch the configuration * @param {string} cacheKey Key that will be used to store cached items to the cache * @param {IPnPClientStore} cacheStore OPTIONAL storage, which will be used to store cached settings. */ function CachingConfigurationProvider(wrappedProvider, cacheKey, cacheStore) { this.wrappedProvider = wrappedProvider; this.cacheKey = cacheKey; this.wrappedProvider = wrappedProvider; this.store = (cacheStore) ? cacheStore : this.selectPnPCache(); } /** * Gets the wrapped configuration providers * * @return {IConfigurationProvider} Wrapped configuration provider */ CachingConfigurationProvider.prototype.getWrappedProvider = function () { return this.wrappedProvider; }; /** * Loads the configuration values either from the cache or from the wrapped provider * * @return {Promise<TypedHash<string>>} Promise of loaded configuration values */ CachingConfigurationProvider.prototype.getConfiguration = function () { var _this = this; // Cache not available, pass control to the wrapped provider if ((!this.store) || (!this.store.enabled)) { return this.wrappedProvider.getConfiguration(); } return this.store.getOrPut(this.cacheKey, function () { return _this.wrappedProvider.getConfiguration().then(function (providedConfig) { _this.store.put(_this.cacheKey, providedConfig); return providedConfig; }); }); }; CachingConfigurationProvider.prototype.selectPnPCache = function () { var pnpCache = new PnPClientStorage(); if ((pnpCache.local) && (pnpCache.local.enabled)) { return pnpCache.local; } if ((pnpCache.session) && (pnpCache.session.enabled)) { return pnpCache.session; } throw new NoCacheAvailableException(); }; return CachingConfigurationProvider; }()); /** * A configuration provider which loads configuration values from a SharePoint list * */ var SPListConfigurationProvider = /** @class */ (function () { /** * Creates a new SharePoint list based configuration provider * @constructor * @param {string} webUrl Url of the SharePoint site, where the configuration list is located * @param {string} listTitle Title of the SharePoint list, which contains the configuration settings (optional, default: "config") * @param {string} keyFieldName The name of the field in the list to use as the setting key (optional, default: "Title") * @param {string} valueFieldName The name of the field in the list to use as the setting value (optional, default: "Value") */ function SPListConfigurationProvider(web, listTitle, keyFieldName, valueFieldName) { if (listTitle === void 0) { listTitle = "config"; } if (keyFieldName === void 0) { keyFieldName = "Title"; } if (valueFieldName === void 0) { valueFieldName = "Value"; } this.web = web; this.listTitle = listTitle; this.keyFieldName = keyFieldName; this.valueFieldName = valueFieldName; } /** * Loads the configuration values from the SharePoint list * * @return {Promise<TypedHash<string>>} Promise of loaded configuration values */ SPListConfigurationProvider.prototype.getConfiguration = function () { var _this = this; return this.web.lists.getByTitle(this.listTitle).items.select(this.keyFieldName, this.valueFieldName).get() .then(function (data) { return data.reduce(function (c, item) { c[item[_this.keyFieldName]] = item[_this.valueFieldName]; return c; }, {}); }); }; /** * Wraps the current provider in a cache enabled provider * * @return {CachingConfigurationProvider} Caching providers which wraps the current provider */ SPListConfigurationProvider.prototype.asCaching = function (cacheKey) { if (cacheKey === void 0) { cacheKey = "pnp_configcache_splist_" + this.web.toUrl() + "+" + this.listTitle; } return new CachingConfigurationProvider(this, cacheKey); }; return SPListConfigurationProvider; }()); export { Settings, CachingConfigurationProvider, SPListConfigurationProvider, NoCacheAvailableException }; //# sourceMappingURL=config-store.es5.js.map
{ return o; }
conditional_block
message-generator.js
'use strict'; const async = require('async'); const _ = require('underscore'); const config = require('../config.json').MessageGenerator; let mixedConfig = _.defaults(config, { sendInterval: 500, deliveryTimeoutTime: 2000, sendNextMessageOnDelivery: false }); module.exports = class MessageGenerator { constructor(scope, nodeManager, messageEmitter) { _.extend(this, mixedConfig); this.scope = scope; this.currentNode = 0; this.nodeManager = nodeManager; this.messageEmitter = messageEmitter; this.lastDeliveryFailed = true; this.lastMessage = null; this.logger = scope.logger; } getMessage() { this.cnt = this.cnt || 0; return this.cnt++; } sendMessage(next) { let nextNode = this.getNextNode(), messageEmitter = this.messageEmitter, nodeName = this.scope.nodeName, publisher = this.scope.publisher; let goNext = () => {} if(next) { goNext = () => { setTimeout(next, this.sendInterval); }; } next = next || () => {}; if(!nextNode) { return goNext(); } if(!this.lastDeliveryFailed || !this.lastMessage) { this.lastMessage = this.getMessage(); } this.lastDeliveryFailed = false; let onDeliveryCallback = () => { clearTimeout(deliveryTimeout); goNext(); }; let deliveryTimeout = setTimeout(() => { this.logger.trace('node dead on delivery', nextNode); messageEmitter.removeListener(`${nodeName}:recieved`,onDeliveryCallback); this.lastDeliveryFailed = true; this.nodeManager.deleteNodeAndSyncAllNodes(nextNode, next); }, this.deliveryTimeoutTime); this.logger.info(`send message ${this.lastMessage}:`, nextNode); messageEmitter.once(`${nodeName}:recieved`, onDeliveryCallback); publisher.publish(`${nextNode}:message`, JSON.stringify({node: nodeName, message: this.lastMessage})); } getNextNode() { let scope = this.scope, nodeList = scope.nodeList, nodeName = scope.nodeName; if(nodeList.length < 2) { return null; } this.currentNode++; if(this.currentNode >= nodeList.length) {
} return nodeList[this.currentNode]; } startSendMessages(callback) { this.scope.publisher.get('currentCounter', (error, counter) => { if(error) { this.cnt = 0 } if(!counter) { this.cnt = 0; } this.messageEmitter.subscribe([`${this.scope.nodeName}:recieved`], () => { if(this.sendNextMessageOnDelivery) { async.forever(this.sendMessage.bind(this)); } else { setInterval(this.sendMessage.bind(this), this.sendInterval) } }); callback(null); }); } }
this.currentNode = 0; } if(nodeList[this.currentNode] === scope.nodeName) { return this.getNextNode();
random_line_split
message-generator.js
'use strict'; const async = require('async'); const _ = require('underscore'); const config = require('../config.json').MessageGenerator; let mixedConfig = _.defaults(config, { sendInterval: 500, deliveryTimeoutTime: 2000, sendNextMessageOnDelivery: false }); module.exports = class MessageGenerator { constructor(scope, nodeManager, messageEmitter) { _.extend(this, mixedConfig); this.scope = scope; this.currentNode = 0; this.nodeManager = nodeManager; this.messageEmitter = messageEmitter; this.lastDeliveryFailed = true; this.lastMessage = null; this.logger = scope.logger; } getMessage() { this.cnt = this.cnt || 0; return this.cnt++; } sendMessage(next) { let nextNode = this.getNextNode(), messageEmitter = this.messageEmitter, nodeName = this.scope.nodeName, publisher = this.scope.publisher; let goNext = () => {} if(next) { goNext = () => { setTimeout(next, this.sendInterval); }; } next = next || () => {}; if(!nextNode) { return goNext(); } if(!this.lastDeliveryFailed || !this.lastMessage) { this.lastMessage = this.getMessage(); } this.lastDeliveryFailed = false; let onDeliveryCallback = () => { clearTimeout(deliveryTimeout); goNext(); }; let deliveryTimeout = setTimeout(() => { this.logger.trace('node dead on delivery', nextNode); messageEmitter.removeListener(`${nodeName}:recieved`,onDeliveryCallback); this.lastDeliveryFailed = true; this.nodeManager.deleteNodeAndSyncAllNodes(nextNode, next); }, this.deliveryTimeoutTime); this.logger.info(`send message ${this.lastMessage}:`, nextNode); messageEmitter.once(`${nodeName}:recieved`, onDeliveryCallback); publisher.publish(`${nextNode}:message`, JSON.stringify({node: nodeName, message: this.lastMessage})); } getNextNode() { let scope = this.scope, nodeList = scope.nodeList, nodeName = scope.nodeName; if(nodeList.length < 2) { return null; } this.currentNode++; if(this.currentNode >= nodeList.length) { this.currentNode = 0; } if(nodeList[this.currentNode] === scope.nodeName) { return this.getNextNode(); } return nodeList[this.currentNode]; } startSendMessages(callback)
}
{ this.scope.publisher.get('currentCounter', (error, counter) => { if(error) { this.cnt = 0 } if(!counter) { this.cnt = 0; } this.messageEmitter.subscribe([`${this.scope.nodeName}:recieved`], () => { if(this.sendNextMessageOnDelivery) { async.forever(this.sendMessage.bind(this)); } else { setInterval(this.sendMessage.bind(this), this.sendInterval) } }); callback(null); }); }
identifier_body
message-generator.js
'use strict'; const async = require('async'); const _ = require('underscore'); const config = require('../config.json').MessageGenerator; let mixedConfig = _.defaults(config, { sendInterval: 500, deliveryTimeoutTime: 2000, sendNextMessageOnDelivery: false }); module.exports = class MessageGenerator { constructor(scope, nodeManager, messageEmitter) { _.extend(this, mixedConfig); this.scope = scope; this.currentNode = 0; this.nodeManager = nodeManager; this.messageEmitter = messageEmitter; this.lastDeliveryFailed = true; this.lastMessage = null; this.logger = scope.logger; } getMessage() { this.cnt = this.cnt || 0; return this.cnt++; } sendMessage(next) { let nextNode = this.getNextNode(), messageEmitter = this.messageEmitter, nodeName = this.scope.nodeName, publisher = this.scope.publisher; let goNext = () => {} if(next) { goNext = () => { setTimeout(next, this.sendInterval); }; } next = next || () => {}; if(!nextNode) { return goNext(); } if(!this.lastDeliveryFailed || !this.lastMessage) { this.lastMessage = this.getMessage(); } this.lastDeliveryFailed = false; let onDeliveryCallback = () => { clearTimeout(deliveryTimeout); goNext(); }; let deliveryTimeout = setTimeout(() => { this.logger.trace('node dead on delivery', nextNode); messageEmitter.removeListener(`${nodeName}:recieved`,onDeliveryCallback); this.lastDeliveryFailed = true; this.nodeManager.deleteNodeAndSyncAllNodes(nextNode, next); }, this.deliveryTimeoutTime); this.logger.info(`send message ${this.lastMessage}:`, nextNode); messageEmitter.once(`${nodeName}:recieved`, onDeliveryCallback); publisher.publish(`${nextNode}:message`, JSON.stringify({node: nodeName, message: this.lastMessage})); } getNextNode() { let scope = this.scope, nodeList = scope.nodeList, nodeName = scope.nodeName; if(nodeList.length < 2) { return null; } this.currentNode++; if(this.currentNode >= nodeList.length) { this.currentNode = 0; } if(nodeList[this.currentNode] === scope.nodeName) { return this.getNextNode(); } return nodeList[this.currentNode]; }
(callback) { this.scope.publisher.get('currentCounter', (error, counter) => { if(error) { this.cnt = 0 } if(!counter) { this.cnt = 0; } this.messageEmitter.subscribe([`${this.scope.nodeName}:recieved`], () => { if(this.sendNextMessageOnDelivery) { async.forever(this.sendMessage.bind(this)); } else { setInterval(this.sendMessage.bind(this), this.sendInterval) } }); callback(null); }); } }
startSendMessages
identifier_name
message-generator.js
'use strict'; const async = require('async'); const _ = require('underscore'); const config = require('../config.json').MessageGenerator; let mixedConfig = _.defaults(config, { sendInterval: 500, deliveryTimeoutTime: 2000, sendNextMessageOnDelivery: false }); module.exports = class MessageGenerator { constructor(scope, nodeManager, messageEmitter) { _.extend(this, mixedConfig); this.scope = scope; this.currentNode = 0; this.nodeManager = nodeManager; this.messageEmitter = messageEmitter; this.lastDeliveryFailed = true; this.lastMessage = null; this.logger = scope.logger; } getMessage() { this.cnt = this.cnt || 0; return this.cnt++; } sendMessage(next) { let nextNode = this.getNextNode(), messageEmitter = this.messageEmitter, nodeName = this.scope.nodeName, publisher = this.scope.publisher; let goNext = () => {} if(next) { goNext = () => { setTimeout(next, this.sendInterval); }; } next = next || () => {}; if(!nextNode) { return goNext(); } if(!this.lastDeliveryFailed || !this.lastMessage) { this.lastMessage = this.getMessage(); } this.lastDeliveryFailed = false; let onDeliveryCallback = () => { clearTimeout(deliveryTimeout); goNext(); }; let deliveryTimeout = setTimeout(() => { this.logger.trace('node dead on delivery', nextNode); messageEmitter.removeListener(`${nodeName}:recieved`,onDeliveryCallback); this.lastDeliveryFailed = true; this.nodeManager.deleteNodeAndSyncAllNodes(nextNode, next); }, this.deliveryTimeoutTime); this.logger.info(`send message ${this.lastMessage}:`, nextNode); messageEmitter.once(`${nodeName}:recieved`, onDeliveryCallback); publisher.publish(`${nextNode}:message`, JSON.stringify({node: nodeName, message: this.lastMessage})); } getNextNode() { let scope = this.scope, nodeList = scope.nodeList, nodeName = scope.nodeName; if(nodeList.length < 2) { return null; } this.currentNode++; if(this.currentNode >= nodeList.length) { this.currentNode = 0; } if(nodeList[this.currentNode] === scope.nodeName) { return this.getNextNode(); } return nodeList[this.currentNode]; } startSendMessages(callback) { this.scope.publisher.get('currentCounter', (error, counter) => { if(error)
if(!counter) { this.cnt = 0; } this.messageEmitter.subscribe([`${this.scope.nodeName}:recieved`], () => { if(this.sendNextMessageOnDelivery) { async.forever(this.sendMessage.bind(this)); } else { setInterval(this.sendMessage.bind(this), this.sendInterval) } }); callback(null); }); } }
{ this.cnt = 0 }
conditional_block
read_exact.rs
use crate::io::AsyncRead; use futures_core::future::Future; use futures_core::ready; use futures_core::task::{Context, Poll}; use std::io; use std::mem; use std::pin::Pin; /// Future for the [`read_exact`](super::AsyncReadExt::read_exact) method. #[derive(Debug)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct ReadExact<'a, R: ?Sized> { reader: &'a mut R, buf: &'a mut [u8], } impl<R: ?Sized + Unpin> Unpin for ReadExact<'_, R> {} impl<'a, R: AsyncRead + ?Sized + Unpin> ReadExact<'a, R> { pub(super) fn new(reader: &'a mut R, buf: &'a mut [u8]) -> Self { Self { reader, buf } } } impl<R: AsyncRead + ?Sized + Unpin> Future for ReadExact<'_, R> { type Output = io::Result<()>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = &mut *self; while !this.buf.is_empty() { let n = ready!(Pin::new(&mut this.reader).poll_read(cx, this.buf))?;
return Poll::Ready(Err(io::ErrorKind::UnexpectedEof.into())); } } Poll::Ready(Ok(())) } }
{ let (_, rest) = mem::replace(&mut this.buf, &mut []).split_at_mut(n); this.buf = rest; } if n == 0 {
random_line_split
read_exact.rs
use crate::io::AsyncRead; use futures_core::future::Future; use futures_core::ready; use futures_core::task::{Context, Poll}; use std::io; use std::mem; use std::pin::Pin; /// Future for the [`read_exact`](super::AsyncReadExt::read_exact) method. #[derive(Debug)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct ReadExact<'a, R: ?Sized> { reader: &'a mut R, buf: &'a mut [u8], } impl<R: ?Sized + Unpin> Unpin for ReadExact<'_, R> {} impl<'a, R: AsyncRead + ?Sized + Unpin> ReadExact<'a, R> { pub(super) fn new(reader: &'a mut R, buf: &'a mut [u8]) -> Self { Self { reader, buf } } } impl<R: AsyncRead + ?Sized + Unpin> Future for ReadExact<'_, R> { type Output = io::Result<()>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = &mut *self; while !this.buf.is_empty() { let n = ready!(Pin::new(&mut this.reader).poll_read(cx, this.buf))?; { let (_, rest) = mem::replace(&mut this.buf, &mut []).split_at_mut(n); this.buf = rest; } if n == 0
} Poll::Ready(Ok(())) } }
{ return Poll::Ready(Err(io::ErrorKind::UnexpectedEof.into())); }
conditional_block
read_exact.rs
use crate::io::AsyncRead; use futures_core::future::Future; use futures_core::ready; use futures_core::task::{Context, Poll}; use std::io; use std::mem; use std::pin::Pin; /// Future for the [`read_exact`](super::AsyncReadExt::read_exact) method. #[derive(Debug)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct ReadExact<'a, R: ?Sized> { reader: &'a mut R, buf: &'a mut [u8], } impl<R: ?Sized + Unpin> Unpin for ReadExact<'_, R> {} impl<'a, R: AsyncRead + ?Sized + Unpin> ReadExact<'a, R> { pub(super) fn new(reader: &'a mut R, buf: &'a mut [u8]) -> Self { Self { reader, buf } } } impl<R: AsyncRead + ?Sized + Unpin> Future for ReadExact<'_, R> { type Output = io::Result<()>; fn
(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = &mut *self; while !this.buf.is_empty() { let n = ready!(Pin::new(&mut this.reader).poll_read(cx, this.buf))?; { let (_, rest) = mem::replace(&mut this.buf, &mut []).split_at_mut(n); this.buf = rest; } if n == 0 { return Poll::Ready(Err(io::ErrorKind::UnexpectedEof.into())); } } Poll::Ready(Ok(())) } }
poll
identifier_name
read_exact.rs
use crate::io::AsyncRead; use futures_core::future::Future; use futures_core::ready; use futures_core::task::{Context, Poll}; use std::io; use std::mem; use std::pin::Pin; /// Future for the [`read_exact`](super::AsyncReadExt::read_exact) method. #[derive(Debug)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct ReadExact<'a, R: ?Sized> { reader: &'a mut R, buf: &'a mut [u8], } impl<R: ?Sized + Unpin> Unpin for ReadExact<'_, R> {} impl<'a, R: AsyncRead + ?Sized + Unpin> ReadExact<'a, R> { pub(super) fn new(reader: &'a mut R, buf: &'a mut [u8]) -> Self { Self { reader, buf } } } impl<R: AsyncRead + ?Sized + Unpin> Future for ReadExact<'_, R> { type Output = io::Result<()>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>
}
{ let this = &mut *self; while !this.buf.is_empty() { let n = ready!(Pin::new(&mut this.reader).poll_read(cx, this.buf))?; { let (_, rest) = mem::replace(&mut this.buf, &mut []).split_at_mut(n); this.buf = rest; } if n == 0 { return Poll::Ready(Err(io::ErrorKind::UnexpectedEof.into())); } } Poll::Ready(Ok(())) }
identifier_body
case207.py
# # Copyright (C) 2004 SIPfoundry Inc. # Licensed by SIPfoundry under the GPL license. # # Copyright (C) 2004 SIP Forum # Licensed to SIPfoundry under a Contributor Agreement. # # # This file is part of SIP Forum User Agent Basic Test Suite which # belongs to the SIP Forum Test Framework. # # SIP Forum User Agent Basic Test Suite 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. # # SIP Forum User Agent Basic Test Suite 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 SIP Forum User Agent Basic Test Suite; if not, write to the # Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # # $Id: case207.py,v 1.2 2004/05/02 18:57:35 lando Exp $ # from TestCase import TestCase import NetworkEventHandler as NEH import Log class
(TestCase): def config(self): self.name = "Case 207" self.description = "Content length larger than message" self.isClient = True self.transport = "UDP" def run(self): self.neh = NEH.NetworkEventHandler(self.transport) inv = self.createRequest("INVITE") cl = inv.getParsedHeaderValue("Content-Length") cl.length = 9999 inv.setHeaderValue("Content-Length", cl.create()) self.writeMessageToNetwork(self.neh, inv) self.code = 0 while (self.code <= 200): repl = self.readReplyFromNetwork(self.neh) if (repl is not None) and (repl.code > self.code): self.code = repl.code elif repl is None: self.code = 999 if repl is None: self.addResult(TestCase.TC_FAILED, "missing reply on request") self.neh.closeSock() def onDefaultCode(self, message): if message.code > self.code: self.code = message.code if message.code >= 200: if message.getParsedHeaderValue("CSeq").method == "INVITE": Log.logDebug("case207: sending ACK for >= 200 reply", 3) ack = self.createRequest("ACK", trans=message.transaction) self.writeMessageToNetwork(self.neh, ack) if message.code == 400: self.addResult(TestCase.TC_PASSED, "INVITE rejected with 400") elif message.code == 200: if message.transaction.canceled: Log.logDebug("case207: received 200 for CANCEL", 3) else: Log.logDebug("case207: sending BYE for accepted INVITE", 3) bye = self.createRequest("BYE", dia=message.transaction.dialog) self.writeMessageToNetwork(self.neh, bye) rep = self.readReplyFromNetwork(self.neh) if rep is None: self.addResult(TestCase.TC_ERROR, "missing response on BYE") elif message.code != 487: self.addResult(TestCase.TC_FAILED, "INVITE rejected, but not with 400") else: self.addResult(TestCase.TC_FAILED, "INVITE accepted, not rejected with 400") can = self.createRequest("CANCEL", trans=message.transaction) message.transaction.canceled = True self.writeMessageToNetwork(self.neh, can) canrepl = self.readReplyFromNetwork(self.neh) if canrepl is None: self.addResult(TestCase.TC_ERROR, "missing 200 on CANCEL")
case207
identifier_name
case207.py
# # Copyright (C) 2004 SIPfoundry Inc. # Licensed by SIPfoundry under the GPL license. # # Copyright (C) 2004 SIP Forum # Licensed to SIPfoundry under a Contributor Agreement. # # # This file is part of SIP Forum User Agent Basic Test Suite which # belongs to the SIP Forum Test Framework. # # SIP Forum User Agent Basic Test Suite 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. # # SIP Forum User Agent Basic Test Suite 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 SIP Forum User Agent Basic Test Suite; if not, write to the # Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # # $Id: case207.py,v 1.2 2004/05/02 18:57:35 lando Exp $ # from TestCase import TestCase import NetworkEventHandler as NEH import Log class case207 (TestCase): def config(self): self.name = "Case 207" self.description = "Content length larger than message" self.isClient = True self.transport = "UDP" def run(self): self.neh = NEH.NetworkEventHandler(self.transport) inv = self.createRequest("INVITE") cl = inv.getParsedHeaderValue("Content-Length") cl.length = 9999 inv.setHeaderValue("Content-Length", cl.create()) self.writeMessageToNetwork(self.neh, inv) self.code = 0 while (self.code <= 200): repl = self.readReplyFromNetwork(self.neh) if (repl is not None) and (repl.code > self.code): self.code = repl.code elif repl is None: self.code = 999 if repl is None: self.addResult(TestCase.TC_FAILED, "missing reply on request") self.neh.closeSock() def onDefaultCode(self, message): if message.code > self.code: self.code = message.code if message.code >= 200: if message.getParsedHeaderValue("CSeq").method == "INVITE": Log.logDebug("case207: sending ACK for >= 200 reply", 3) ack = self.createRequest("ACK", trans=message.transaction) self.writeMessageToNetwork(self.neh, ack) if message.code == 400: self.addResult(TestCase.TC_PASSED, "INVITE rejected with 400") elif message.code == 200: if message.transaction.canceled: Log.logDebug("case207: received 200 for CANCEL", 3) else: Log.logDebug("case207: sending BYE for accepted INVITE", 3) bye = self.createRequest("BYE", dia=message.transaction.dialog) self.writeMessageToNetwork(self.neh, bye) rep = self.readReplyFromNetwork(self.neh) if rep is None: self.addResult(TestCase.TC_ERROR, "missing response on BYE") elif message.code != 487:
else: self.addResult(TestCase.TC_FAILED, "INVITE accepted, not rejected with 400") can = self.createRequest("CANCEL", trans=message.transaction) message.transaction.canceled = True self.writeMessageToNetwork(self.neh, can) canrepl = self.readReplyFromNetwork(self.neh) if canrepl is None: self.addResult(TestCase.TC_ERROR, "missing 200 on CANCEL")
self.addResult(TestCase.TC_FAILED, "INVITE rejected, but not with 400")
conditional_block
case207.py
# # Copyright (C) 2004 SIPfoundry Inc. # Licensed by SIPfoundry under the GPL license. # # Copyright (C) 2004 SIP Forum # Licensed to SIPfoundry under a Contributor Agreement. # # # This file is part of SIP Forum User Agent Basic Test Suite which # belongs to the SIP Forum Test Framework. # # SIP Forum User Agent Basic Test Suite 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. # # SIP Forum User Agent Basic Test Suite 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 SIP Forum User Agent Basic Test Suite; if not, write to the # Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # # $Id: case207.py,v 1.2 2004/05/02 18:57:35 lando Exp $ # from TestCase import TestCase import NetworkEventHandler as NEH import Log class case207 (TestCase): def config(self): self.name = "Case 207" self.description = "Content length larger than message" self.isClient = True self.transport = "UDP" def run(self):
def onDefaultCode(self, message): if message.code > self.code: self.code = message.code if message.code >= 200: if message.getParsedHeaderValue("CSeq").method == "INVITE": Log.logDebug("case207: sending ACK for >= 200 reply", 3) ack = self.createRequest("ACK", trans=message.transaction) self.writeMessageToNetwork(self.neh, ack) if message.code == 400: self.addResult(TestCase.TC_PASSED, "INVITE rejected with 400") elif message.code == 200: if message.transaction.canceled: Log.logDebug("case207: received 200 for CANCEL", 3) else: Log.logDebug("case207: sending BYE for accepted INVITE", 3) bye = self.createRequest("BYE", dia=message.transaction.dialog) self.writeMessageToNetwork(self.neh, bye) rep = self.readReplyFromNetwork(self.neh) if rep is None: self.addResult(TestCase.TC_ERROR, "missing response on BYE") elif message.code != 487: self.addResult(TestCase.TC_FAILED, "INVITE rejected, but not with 400") else: self.addResult(TestCase.TC_FAILED, "INVITE accepted, not rejected with 400") can = self.createRequest("CANCEL", trans=message.transaction) message.transaction.canceled = True self.writeMessageToNetwork(self.neh, can) canrepl = self.readReplyFromNetwork(self.neh) if canrepl is None: self.addResult(TestCase.TC_ERROR, "missing 200 on CANCEL")
self.neh = NEH.NetworkEventHandler(self.transport) inv = self.createRequest("INVITE") cl = inv.getParsedHeaderValue("Content-Length") cl.length = 9999 inv.setHeaderValue("Content-Length", cl.create()) self.writeMessageToNetwork(self.neh, inv) self.code = 0 while (self.code <= 200): repl = self.readReplyFromNetwork(self.neh) if (repl is not None) and (repl.code > self.code): self.code = repl.code elif repl is None: self.code = 999 if repl is None: self.addResult(TestCase.TC_FAILED, "missing reply on request") self.neh.closeSock()
identifier_body
case207.py
# # Copyright (C) 2004 SIP Forum # Licensed to SIPfoundry under a Contributor Agreement. # # # This file is part of SIP Forum User Agent Basic Test Suite which # belongs to the SIP Forum Test Framework. # # SIP Forum User Agent Basic Test Suite 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. # # SIP Forum User Agent Basic Test Suite 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 SIP Forum User Agent Basic Test Suite; if not, write to the # Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # # $Id: case207.py,v 1.2 2004/05/02 18:57:35 lando Exp $ # from TestCase import TestCase import NetworkEventHandler as NEH import Log class case207 (TestCase): def config(self): self.name = "Case 207" self.description = "Content length larger than message" self.isClient = True self.transport = "UDP" def run(self): self.neh = NEH.NetworkEventHandler(self.transport) inv = self.createRequest("INVITE") cl = inv.getParsedHeaderValue("Content-Length") cl.length = 9999 inv.setHeaderValue("Content-Length", cl.create()) self.writeMessageToNetwork(self.neh, inv) self.code = 0 while (self.code <= 200): repl = self.readReplyFromNetwork(self.neh) if (repl is not None) and (repl.code > self.code): self.code = repl.code elif repl is None: self.code = 999 if repl is None: self.addResult(TestCase.TC_FAILED, "missing reply on request") self.neh.closeSock() def onDefaultCode(self, message): if message.code > self.code: self.code = message.code if message.code >= 200: if message.getParsedHeaderValue("CSeq").method == "INVITE": Log.logDebug("case207: sending ACK for >= 200 reply", 3) ack = self.createRequest("ACK", trans=message.transaction) self.writeMessageToNetwork(self.neh, ack) if message.code == 400: self.addResult(TestCase.TC_PASSED, "INVITE rejected with 400") elif message.code == 200: if message.transaction.canceled: Log.logDebug("case207: received 200 for CANCEL", 3) else: Log.logDebug("case207: sending BYE for accepted INVITE", 3) bye = self.createRequest("BYE", dia=message.transaction.dialog) self.writeMessageToNetwork(self.neh, bye) rep = self.readReplyFromNetwork(self.neh) if rep is None: self.addResult(TestCase.TC_ERROR, "missing response on BYE") elif message.code != 487: self.addResult(TestCase.TC_FAILED, "INVITE rejected, but not with 400") else: self.addResult(TestCase.TC_FAILED, "INVITE accepted, not rejected with 400") can = self.createRequest("CANCEL", trans=message.transaction) message.transaction.canceled = True self.writeMessageToNetwork(self.neh, can) canrepl = self.readReplyFromNetwork(self.neh) if canrepl is None: self.addResult(TestCase.TC_ERROR, "missing 200 on CANCEL")
# # Copyright (C) 2004 SIPfoundry Inc. # Licensed by SIPfoundry under the GPL license.
random_line_split
TeamEntity.test.ts
/* * Wire * Copyright (C) 2019 Wire Swiss GmbH * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses/. * */ import {TeamEntity} from './TeamEntity'; describe('TeamEntity', () => { it('returns an icon resource', () => { const teamEntity = new TeamEntity(); expect(teamEntity.getIconResource()).not.toBeDefined(); teamEntity.icon = 'invalid-icon'; expect(teamEntity.getIconResource()).not.toBeDefined(); teamEntity.icon = '3-1-e705c3f5-7b4b-4136-a09b-01614cb355a1'; expect(teamEntity.getIconResource()).toBeDefined(); }); });
random_line_split
crawler.py
#!/usr/bin/env python #encoding:utf-8 import os import sys import requests import MySQLdb from bs4 import BeautifulSoup from bs4 import SoupStrainer if len(sys.argv) != 4: print 'Invalid parameters!' exit(1)
start_point = (int(sys.argv[2]), int(sys.argv[3])) immediate_download = False base_url = 'http://www.3che.com' session = requests.Session() username = '' password = '' record = { 'category': '', 'detail_category': '', 'post_url': '', 'filename': '', 'url': '' } sql_cnt = 0 connection = None cursor = None def record_to_mysql(): global sql_cnt, connection, cursor if sql_cnt % 20 == 0: if connection: connection.commit() connection.close() cursor.close() connection = MySQLdb.connect(host='', user='', passwd='', db='', port=3306, charset='utf8') cursor = connection.cursor() sql_cnt += 1 cursor.execute('insert into san_che(`category`, `detail_category`, `post_url`, `filename`, `url`) values (%s, %s, %s, %s, %s)', (record['category'], record['detail_category'], record['post_url'], record['filename'], record['url'])) def login(): login_path = '/member.php?mod=logging&action=login&loginsubmit=yes&infloat=yes&lssubmit=yes&inajax=1' session.post(base_url + login_path, {'username': username, 'password': password}) def enter_directory(name): if immediate_download: if not os.path.exists(name): os.mkdir(name) os.chdir(name) def get_soup(url, parse_only=None): text = session.get(url).text return BeautifulSoup(text, 'lxml', parse_only=parse_only) def download_file(url, filename): print 'Downloading:', filename, '=>', url record['url'] = url record['filename'] = filename if immediate_download: with open(filename, 'w') as fp: res = requests.get(url) fp.write(res.content) fp.close() else: record_to_mysql() def crawl_file(url, filename): try: soup = get_soup(url, SoupStrainer(id='attachpayform')) attach_form = soup.find('form', id='attachpayform') link = attach_form.table.find_all('a')[-1] except Exception as e: print 'Error! file url:', url else: download_file(link['href'], filename) # Crawl detail data of one post. def crawl_detail(detail_category, title, detail_url): print '-' * 100 print 'Crawling Post:', detail_category, title, '=>', detail_url record['detail_category'] = detail_category record['post_url'] = detail_url # Enter detail directory. enter_directory(detail_category) prefix = detail_url.rsplit('/', 1)[-1].split('.', 1)[0] enter_directory(prefix + title) soup = get_soup(detail_url, SoupStrainer('p', {'class': 'attnm'})) attnms = soup.find_all('p', {'class': 'attnm'}) for attnm in attnms: url = '{0}/{1}'.format(base_url, attnm.a['href']) crawl_file(url, attnm.a.text.strip(u'[下载]')) # Leave detail directory. if immediate_download: os.chdir('../..') # Crawl data of one category. def crawl_category(category, list_url): print '=' * 100 print 'Crawling category:', category, '=>', list_url record['category'] = category # Create corresponding directory and enter. enter_directory(category) cur_page_id = 0 url = list_url while url is not None: cur_page_id += 1 print 'Crawling page url:', url soup = get_soup(url, SoupStrainer('span')) xsts = soup.find_all('span', {'class': 'xst'}) if cur_page_id >= start_point[0]: cur_in_page_id = 0 for xst in xsts: cur_in_page_id += 1 detail = xst.find('a', {'class': 'xst'}) if cur_page_id > start_point[0] or cur_in_page_id >= start_point[1]: crawl_detail(xst.em and xst.em.a.text or '', detail.text, detail['href']) page_footer = soup.find('span', id='fd_page_top') next_link = page_footer.label.next_sibling if next_link is not None: url = next_link['href'] else: url = None # Leave the directory. if immediate_download: os.chdir('..') if __name__ == '__main__': login() # Extract categories from home page. soup = get_soup(base_url, SoupStrainer(id='nv')) category_lis = soup.find('div', id='nv').ul.find_all('li') categories = map(lambda x: (x.a.text, x.a['href']), category_lis) categories = filter(lambda x: x[1] != '/', categories) crawl_category(categories[aim_category_id][0], categories[aim_category_id][1]) # for category in categories: # crawl_category(category[0], category[1])
print '=' * 60 print 'start:', sys.argv aim_category_id = int(sys.argv[1])
random_line_split
crawler.py
#!/usr/bin/env python #encoding:utf-8 import os import sys import requests import MySQLdb from bs4 import BeautifulSoup from bs4 import SoupStrainer if len(sys.argv) != 4: print 'Invalid parameters!' exit(1) print '=' * 60 print 'start:', sys.argv aim_category_id = int(sys.argv[1]) start_point = (int(sys.argv[2]), int(sys.argv[3])) immediate_download = False base_url = 'http://www.3che.com' session = requests.Session() username = '' password = '' record = { 'category': '', 'detail_category': '', 'post_url': '', 'filename': '', 'url': '' } sql_cnt = 0 connection = None cursor = None def record_to_mysql(): global sql_cnt, connection, cursor if sql_cnt % 20 == 0: if connection: connection.commit() connection.close() cursor.close() connection = MySQLdb.connect(host='', user='', passwd='', db='', port=3306, charset='utf8') cursor = connection.cursor() sql_cnt += 1 cursor.execute('insert into san_che(`category`, `detail_category`, `post_url`, `filename`, `url`) values (%s, %s, %s, %s, %s)', (record['category'], record['detail_category'], record['post_url'], record['filename'], record['url'])) def login(): login_path = '/member.php?mod=logging&action=login&loginsubmit=yes&infloat=yes&lssubmit=yes&inajax=1' session.post(base_url + login_path, {'username': username, 'password': password}) def enter_directory(name): if immediate_download: if not os.path.exists(name): os.mkdir(name) os.chdir(name) def get_soup(url, parse_only=None): text = session.get(url).text return BeautifulSoup(text, 'lxml', parse_only=parse_only) def download_file(url, filename): print 'Downloading:', filename, '=>', url record['url'] = url record['filename'] = filename if immediate_download: with open(filename, 'w') as fp: res = requests.get(url) fp.write(res.content) fp.close() else: record_to_mysql() def crawl_file(url, filename): try: soup = get_soup(url, SoupStrainer(id='attachpayform')) attach_form = soup.find('form', id='attachpayform') link = attach_form.table.find_all('a')[-1] except Exception as e: print 'Error! file url:', url else: download_file(link['href'], filename) # Crawl detail data of one post. def crawl_detail(detail_category, title, detail_url): print '-' * 100 print 'Crawling Post:', detail_category, title, '=>', detail_url record['detail_category'] = detail_category record['post_url'] = detail_url # Enter detail directory. enter_directory(detail_category) prefix = detail_url.rsplit('/', 1)[-1].split('.', 1)[0] enter_directory(prefix + title) soup = get_soup(detail_url, SoupStrainer('p', {'class': 'attnm'})) attnms = soup.find_all('p', {'class': 'attnm'}) for attnm in attnms: url = '{0}/{1}'.format(base_url, attnm.a['href']) crawl_file(url, attnm.a.text.strip(u'[下载]')) # Leave detail directory. if immediate_download: os.chdir('../..') # Crawl data of one category. def crawl_category(category, list_url): print '=' * 100 print 'Crawling category:', category, '=>', list_url record['category'] = category # Create corresponding directory and enter. enter_directory(category) cur_page_id = 0 url = list_url while url is not None: cur_page_id += 1 print 'Crawling page url:', url soup = get_soup(url, SoupStrainer('span')) xsts = soup.find_all('span', {'class': 'xst'}) if cur_page_id >= start_point[0]: cur_in_page_id = 0 for xst in xsts: cur_in_page_id += 1 detail = xst.find('a', {'class': 'xst'}) if cur_page_id > start_point[0] or cur_in_page_id >= start_point[1]: crawl_detail(xst.em and xst.em.a.text or '', detail.text, detail['href']) page_footer = soup.find('span', id='fd_page_top') next_link = page_footer.label.next_sibling if next_link is not None: url = next_link['href'] else: url = None # Leave the directory. if immediate_download: os.chdir('..') if __name__ == '__main__': logi
n() # Extract categories from home page. soup = get_soup(base_url, SoupStrainer(id='nv')) category_lis = soup.find('div', id='nv').ul.find_all('li') categories = map(lambda x: (x.a.text, x.a['href']), category_lis) categories = filter(lambda x: x[1] != '/', categories) crawl_category(categories[aim_category_id][0], categories[aim_category_id][1]) # for category in categories: # crawl_category(category[0], category[1])
conditional_block
crawler.py
#!/usr/bin/env python #encoding:utf-8 import os import sys import requests import MySQLdb from bs4 import BeautifulSoup from bs4 import SoupStrainer if len(sys.argv) != 4: print 'Invalid parameters!' exit(1) print '=' * 60 print 'start:', sys.argv aim_category_id = int(sys.argv[1]) start_point = (int(sys.argv[2]), int(sys.argv[3])) immediate_download = False base_url = 'http://www.3che.com' session = requests.Session() username = '' password = '' record = { 'category': '', 'detail_category': '', 'post_url': '', 'filename': '', 'url': '' } sql_cnt = 0 connection = None cursor = None def record_to_mysql(): global sql_cnt, connection, cursor if sql_cnt % 20 == 0: if connection: connection.commit() connection.close() cursor.close() connection = MySQLdb.connect(host='', user='', passwd='', db='', port=3306, charset='utf8') cursor = connection.cursor() sql_cnt += 1 cursor.execute('insert into san_che(`category`, `detail_category`, `post_url`, `filename`, `url`) values (%s, %s, %s, %s, %s)', (record['category'], record['detail_category'], record['post_url'], record['filename'], record['url'])) def login(): login_path = '/member.php?mod=logging&action=login&loginsubmit=yes&infloat=yes&lssubmit=yes&inajax=1' session.post(base_url + login_path, {'username': username, 'password': password}) def enter_directory(name): if immediate_download: if not os.path.exists(name): os.mkdir(name) os.chdir(name) def get_soup(url, parse_only=None): text = session.get(url).text return BeautifulSoup(text, 'lxml', parse_only=parse_only) def download_file(url, filename):
def crawl_file(url, filename): try: soup = get_soup(url, SoupStrainer(id='attachpayform')) attach_form = soup.find('form', id='attachpayform') link = attach_form.table.find_all('a')[-1] except Exception as e: print 'Error! file url:', url else: download_file(link['href'], filename) # Crawl detail data of one post. def crawl_detail(detail_category, title, detail_url): print '-' * 100 print 'Crawling Post:', detail_category, title, '=>', detail_url record['detail_category'] = detail_category record['post_url'] = detail_url # Enter detail directory. enter_directory(detail_category) prefix = detail_url.rsplit('/', 1)[-1].split('.', 1)[0] enter_directory(prefix + title) soup = get_soup(detail_url, SoupStrainer('p', {'class': 'attnm'})) attnms = soup.find_all('p', {'class': 'attnm'}) for attnm in attnms: url = '{0}/{1}'.format(base_url, attnm.a['href']) crawl_file(url, attnm.a.text.strip(u'[下载]')) # Leave detail directory. if immediate_download: os.chdir('../..') # Crawl data of one category. def crawl_category(category, list_url): print '=' * 100 print 'Crawling category:', category, '=>', list_url record['category'] = category # Create corresponding directory and enter. enter_directory(category) cur_page_id = 0 url = list_url while url is not None: cur_page_id += 1 print 'Crawling page url:', url soup = get_soup(url, SoupStrainer('span')) xsts = soup.find_all('span', {'class': 'xst'}) if cur_page_id >= start_point[0]: cur_in_page_id = 0 for xst in xsts: cur_in_page_id += 1 detail = xst.find('a', {'class': 'xst'}) if cur_page_id > start_point[0] or cur_in_page_id >= start_point[1]: crawl_detail(xst.em and xst.em.a.text or '', detail.text, detail['href']) page_footer = soup.find('span', id='fd_page_top') next_link = page_footer.label.next_sibling if next_link is not None: url = next_link['href'] else: url = None # Leave the directory. if immediate_download: os.chdir('..') if __name__ == '__main__': login() # Extract categories from home page. soup = get_soup(base_url, SoupStrainer(id='nv')) category_lis = soup.find('div', id='nv').ul.find_all('li') categories = map(lambda x: (x.a.text, x.a['href']), category_lis) categories = filter(lambda x: x[1] != '/', categories) crawl_category(categories[aim_category_id][0], categories[aim_category_id][1]) # for category in categories: # crawl_category(category[0], category[1])
print 'Downloading:', filename, '=>', url record['url'] = url record['filename'] = filename if immediate_download: with open(filename, 'w') as fp: res = requests.get(url) fp.write(res.content) fp.close() else: record_to_mysql()
identifier_body
crawler.py
#!/usr/bin/env python #encoding:utf-8 import os import sys import requests import MySQLdb from bs4 import BeautifulSoup from bs4 import SoupStrainer if len(sys.argv) != 4: print 'Invalid parameters!' exit(1) print '=' * 60 print 'start:', sys.argv aim_category_id = int(sys.argv[1]) start_point = (int(sys.argv[2]), int(sys.argv[3])) immediate_download = False base_url = 'http://www.3che.com' session = requests.Session() username = '' password = '' record = { 'category': '', 'detail_category': '', 'post_url': '', 'filename': '', 'url': '' } sql_cnt = 0 connection = None cursor = None def record_to_mysql(): global sql_cnt, connection, cursor if sql_cnt % 20 == 0: if connection: connection.commit() connection.close() cursor.close() connection = MySQLdb.connect(host='', user='', passwd='', db='', port=3306, charset='utf8') cursor = connection.cursor() sql_cnt += 1 cursor.execute('insert into san_che(`category`, `detail_category`, `post_url`, `filename`, `url`) values (%s, %s, %s, %s, %s)', (record['category'], record['detail_category'], record['post_url'], record['filename'], record['url'])) def login(): login_path = '/member.php?mod=logging&action=login&loginsubmit=yes&infloat=yes&lssubmit=yes&inajax=1' session.post(base_url + login_path, {'username': username, 'password': password}) def enter_directory(name): if immediate_download: if not os.path.exists(name): os.mkdir(name) os.chdir(name) def
(url, parse_only=None): text = session.get(url).text return BeautifulSoup(text, 'lxml', parse_only=parse_only) def download_file(url, filename): print 'Downloading:', filename, '=>', url record['url'] = url record['filename'] = filename if immediate_download: with open(filename, 'w') as fp: res = requests.get(url) fp.write(res.content) fp.close() else: record_to_mysql() def crawl_file(url, filename): try: soup = get_soup(url, SoupStrainer(id='attachpayform')) attach_form = soup.find('form', id='attachpayform') link = attach_form.table.find_all('a')[-1] except Exception as e: print 'Error! file url:', url else: download_file(link['href'], filename) # Crawl detail data of one post. def crawl_detail(detail_category, title, detail_url): print '-' * 100 print 'Crawling Post:', detail_category, title, '=>', detail_url record['detail_category'] = detail_category record['post_url'] = detail_url # Enter detail directory. enter_directory(detail_category) prefix = detail_url.rsplit('/', 1)[-1].split('.', 1)[0] enter_directory(prefix + title) soup = get_soup(detail_url, SoupStrainer('p', {'class': 'attnm'})) attnms = soup.find_all('p', {'class': 'attnm'}) for attnm in attnms: url = '{0}/{1}'.format(base_url, attnm.a['href']) crawl_file(url, attnm.a.text.strip(u'[下载]')) # Leave detail directory. if immediate_download: os.chdir('../..') # Crawl data of one category. def crawl_category(category, list_url): print '=' * 100 print 'Crawling category:', category, '=>', list_url record['category'] = category # Create corresponding directory and enter. enter_directory(category) cur_page_id = 0 url = list_url while url is not None: cur_page_id += 1 print 'Crawling page url:', url soup = get_soup(url, SoupStrainer('span')) xsts = soup.find_all('span', {'class': 'xst'}) if cur_page_id >= start_point[0]: cur_in_page_id = 0 for xst in xsts: cur_in_page_id += 1 detail = xst.find('a', {'class': 'xst'}) if cur_page_id > start_point[0] or cur_in_page_id >= start_point[1]: crawl_detail(xst.em and xst.em.a.text or '', detail.text, detail['href']) page_footer = soup.find('span', id='fd_page_top') next_link = page_footer.label.next_sibling if next_link is not None: url = next_link['href'] else: url = None # Leave the directory. if immediate_download: os.chdir('..') if __name__ == '__main__': login() # Extract categories from home page. soup = get_soup(base_url, SoupStrainer(id='nv')) category_lis = soup.find('div', id='nv').ul.find_all('li') categories = map(lambda x: (x.a.text, x.a['href']), category_lis) categories = filter(lambda x: x[1] != '/', categories) crawl_category(categories[aim_category_id][0], categories[aim_category_id][1]) # for category in categories: # crawl_category(category[0], category[1])
get_soup
identifier_name
extra_tags.py
import time import os import posixpath import datetime import math import re import logging from django import template from django.utils.encoding import smart_unicode from django.utils.safestring import mark_safe from forum.models import Question, Answer, QuestionRevision, AnswerRevision, NodeRevision from django.utils.translation import ugettext as _ from django.utils.translation import ungettext from django.utils import simplejson from forum import settings from django.template.defaulttags import url as default_url from forum import skins from forum.utils import html from extra_filters import decorated_int from django.core.urlresolvers import reverse register = template.Library() GRAVATAR_TEMPLATE = ('<img class="gravatar" width="%(size)s" height="%(size)s" ' 'src="http://www.gravatar.com/avatar/%(gravatar_hash)s' '?s=%(size)s&amp;d=%(default)s&amp;r=%(rating)s" ' 'alt="%(username)s\'s gravatar image" />') @register.simple_tag def gravatar(user, size): try: gravatar = user['gravatar'] username = user['username'] except (TypeError, AttributeError, KeyError): gravatar = user.gravatar username = user.username return mark_safe(GRAVATAR_TEMPLATE % { 'size': size, 'gravatar_hash': gravatar, 'default': settings.GRAVATAR_DEFAULT_IMAGE, 'rating': settings.GRAVATAR_ALLOWED_RATING, 'username': template.defaultfilters.urlencode(username), }) @register.simple_tag def get_score_badge(user): if user.is_suspended(): return _("(suspended)") repstr = decorated_int(user.reputation, "") BADGE_TEMPLATE = '<span class="score" title="%(reputation)s %(reputationword)s">%(repstr)s</span>' if user.gold > 0 : BADGE_TEMPLATE = '%s%s' % (BADGE_TEMPLATE, '<span title="%(gold)s %(badgesword)s">' '<span class="badge1">&#9679;</span>' '<span class="badgecount">%(gold)s</span>' '</span>') if user.silver > 0: BADGE_TEMPLATE = '%s%s' % (BADGE_TEMPLATE, '<span title="%(silver)s %(badgesword)s">' '<span class="silver">&#9679;</span>' '<span class="badgecount">%(silver)s</span>' '</span>') if user.bronze > 0: BADGE_TEMPLATE = '%s%s' % (BADGE_TEMPLATE, '<span title="%(bronze)s %(badgesword)s">' '<span class="bronze">&#9679;</span>' '<span class="badgecount">%(bronze)s</span>' '</span>') BADGE_TEMPLATE = smart_unicode(BADGE_TEMPLATE, encoding='utf-8', strings_only=False, errors='strict') return mark_safe(BADGE_TEMPLATE % { 'reputation' : user.reputation, 'repstr': repstr, 'gold' : user.gold, 'silver' : user.silver, 'bronze' : user.bronze, 'badgesword' : _('badges'), 'reputationword' : _('reputation points'), }) @register.simple_tag def get_age(birthday): current_time = datetime.datetime(*time.localtime()[0:6]) year = birthday.year month = birthday.month day = birthday.day diff = current_time - datetime.datetime(year, month, day, 0, 0, 0) return diff.days / 365 @register.simple_tag def diff_date(date, limen=2): if not date: return _('unknown') now = datetime.datetime.now() diff = now - date days = diff.days hours = int(diff.seconds/3600) minutes = int(diff.seconds/60) if days > 2: if date.year == now.year: return date.strftime(_("%b %d at %H:%M").encode()) else: return date.strftime(_("%b %d '%y at %H:%M").encode()) elif days == 2: return _('2 days ago') elif days == 1: return _('yesterday') elif minutes >= 60: return ungettext('%(hr)d ' + _("hour ago"), '%(hr)d ' + _("hours ago"), hours) % {'hr':hours} elif diff.seconds >= 60: return ungettext('%(min)d ' + _("min ago"), '%(min)d ' + _("mins ago"), minutes) % {'min':minutes} else: return ungettext('%(sec)d ' + _("sec ago"), '%(sec)d ' + _("secs ago"), diff.seconds) % {'sec':diff.seconds} @register.simple_tag def media(url): url = skins.find_media_source(url) if url: # Create the URL prefix. url_prefix = settings.FORCE_SCRIPT_NAME + '/m/' # Make sure any duplicate forward slashes are replaced with a single # forward slash. url_prefix = re.sub("/+", "/", url_prefix) url = url_prefix + url return url class ItemSeparatorNode(template.Node): def __init__(self, separator): sep = separator.strip() if sep[0] == sep[-1] and sep[0] in ('\'', '"'): sep = sep[1:-1] else: raise template.TemplateSyntaxError('separator in joinitems tag must be quoted') self.content = sep def render(self, context): return self.content class BlockMediaUrlNode(template.Node): def __init__(self, nodelist): self.items = nodelist def render(self, context): prefix = settings.APP_URL + 'm/' url = '' if self.items: url += '/' for item in self.items: url += item.render(context) url = skins.find_media_source(url) url = prefix + url out = url return out.replace(' ', '') @register.tag(name='blockmedia') def blockmedia(parser, token): try: tagname = token.split_contents() except ValueError: raise template.TemplateSyntaxError("blockmedia tag does not use arguments") nodelist = [] while True: nodelist.append(parser.parse(('endblockmedia'))) next = parser.next_token() if next.contents == 'endblockmedia': break return BlockMediaUrlNode(nodelist) @register.simple_tag def fullmedia(url): domain = settings.APP_BASE_URL #protocol = getattr(settings, "PROTOCOL", "http") path = media(url) return "%s%s" % (domain, path) class SimpleVarNode(template.Node): def __init__(self, name, value): self.name = name self.value = template.Variable(value) def render(self, context): context[self.name] = self.value.resolve(context) return '' class BlockVarNode(template.Node): def __init__(self, name, block): self.name = name self.block = block def render(self, context):
@register.tag(name='var') def do_var(parser, token): tokens = token.split_contents()[1:] if not len(tokens) or not re.match('^\w+$', tokens[0]): raise template.TemplateSyntaxError("Expected variable name") if len(tokens) == 1: nodelist = parser.parse(('endvar',)) parser.delete_first_token() return BlockVarNode(tokens[0], nodelist) elif len(tokens) == 3: return SimpleVarNode(tokens[0], tokens[2]) raise template.TemplateSyntaxError("Invalid number of arguments") class DeclareNode(template.Node): dec_re = re.compile('^\s*(\w+)\s*(:?=)\s*(.*)$') def __init__(self, block): self.block = block def render(self, context): source = self.block.render(context) for line in source.splitlines(): m = self.dec_re.search(line) if m: clist = list(context) clist.reverse() d = {} d['_'] = _ d['os'] = os d['html'] = html d['reverse'] = reverse for c in clist: d.update(c) try: context[m.group(1).strip()] = eval(m.group(3).strip(), d) except Exception, e: logging.error("Error in declare tag, when evaluating: %s" % m.group(3).strip()) raise return '' @register.tag(name='declare') def do_declare(parser, token): nodelist = parser.parse(('enddeclare',)) parser.delete_first_token() return DeclareNode(nodelist)
source = self.block.render(context) context[self.name] = source.strip() return ''
identifier_body
extra_tags.py
import time import os import posixpath import datetime import math import re import logging from django import template from django.utils.encoding import smart_unicode from django.utils.safestring import mark_safe from forum.models import Question, Answer, QuestionRevision, AnswerRevision, NodeRevision from django.utils.translation import ugettext as _ from django.utils.translation import ungettext from django.utils import simplejson from forum import settings from django.template.defaulttags import url as default_url from forum import skins from forum.utils import html from extra_filters import decorated_int from django.core.urlresolvers import reverse register = template.Library() GRAVATAR_TEMPLATE = ('<img class="gravatar" width="%(size)s" height="%(size)s" ' 'src="http://www.gravatar.com/avatar/%(gravatar_hash)s' '?s=%(size)s&amp;d=%(default)s&amp;r=%(rating)s" ' 'alt="%(username)s\'s gravatar image" />') @register.simple_tag def gravatar(user, size): try: gravatar = user['gravatar'] username = user['username'] except (TypeError, AttributeError, KeyError): gravatar = user.gravatar username = user.username return mark_safe(GRAVATAR_TEMPLATE % { 'size': size, 'gravatar_hash': gravatar, 'default': settings.GRAVATAR_DEFAULT_IMAGE, 'rating': settings.GRAVATAR_ALLOWED_RATING, 'username': template.defaultfilters.urlencode(username), }) @register.simple_tag def get_score_badge(user): if user.is_suspended(): return _("(suspended)") repstr = decorated_int(user.reputation, "") BADGE_TEMPLATE = '<span class="score" title="%(reputation)s %(reputationword)s">%(repstr)s</span>' if user.gold > 0 : BADGE_TEMPLATE = '%s%s' % (BADGE_TEMPLATE, '<span title="%(gold)s %(badgesword)s">' '<span class="badge1">&#9679;</span>' '<span class="badgecount">%(gold)s</span>' '</span>') if user.silver > 0: BADGE_TEMPLATE = '%s%s' % (BADGE_TEMPLATE, '<span title="%(silver)s %(badgesword)s">' '<span class="silver">&#9679;</span>' '<span class="badgecount">%(silver)s</span>' '</span>') if user.bronze > 0: BADGE_TEMPLATE = '%s%s' % (BADGE_TEMPLATE, '<span title="%(bronze)s %(badgesword)s">' '<span class="bronze">&#9679;</span>' '<span class="badgecount">%(bronze)s</span>' '</span>') BADGE_TEMPLATE = smart_unicode(BADGE_TEMPLATE, encoding='utf-8', strings_only=False, errors='strict') return mark_safe(BADGE_TEMPLATE % { 'reputation' : user.reputation, 'repstr': repstr, 'gold' : user.gold, 'silver' : user.silver, 'bronze' : user.bronze, 'badgesword' : _('badges'), 'reputationword' : _('reputation points'), }) @register.simple_tag def get_age(birthday): current_time = datetime.datetime(*time.localtime()[0:6]) year = birthday.year month = birthday.month day = birthday.day diff = current_time - datetime.datetime(year, month, day, 0, 0, 0) return diff.days / 365 @register.simple_tag def diff_date(date, limen=2): if not date: return _('unknown') now = datetime.datetime.now() diff = now - date days = diff.days hours = int(diff.seconds/3600) minutes = int(diff.seconds/60) if days > 2: if date.year == now.year: return date.strftime(_("%b %d at %H:%M").encode()) else: return date.strftime(_("%b %d '%y at %H:%M").encode()) elif days == 2: return _('2 days ago') elif days == 1: return _('yesterday') elif minutes >= 60: return ungettext('%(hr)d ' + _("hour ago"), '%(hr)d ' + _("hours ago"), hours) % {'hr':hours} elif diff.seconds >= 60: return ungettext('%(min)d ' + _("min ago"), '%(min)d ' + _("mins ago"), minutes) % {'min':minutes} else: return ungettext('%(sec)d ' + _("sec ago"), '%(sec)d ' + _("secs ago"), diff.seconds) % {'sec':diff.seconds} @register.simple_tag def media(url): url = skins.find_media_source(url) if url: # Create the URL prefix. url_prefix = settings.FORCE_SCRIPT_NAME + '/m/' # Make sure any duplicate forward slashes are replaced with a single # forward slash. url_prefix = re.sub("/+", "/", url_prefix) url = url_prefix + url return url class ItemSeparatorNode(template.Node): def __init__(self, separator): sep = separator.strip() if sep[0] == sep[-1] and sep[0] in ('\'', '"'): sep = sep[1:-1] else: raise template.TemplateSyntaxError('separator in joinitems tag must be quoted') self.content = sep def render(self, context): return self.content class BlockMediaUrlNode(template.Node): def __init__(self, nodelist): self.items = nodelist def render(self, context): prefix = settings.APP_URL + 'm/' url = '' if self.items: url += '/' for item in self.items: url += item.render(context) url = skins.find_media_source(url) url = prefix + url out = url return out.replace(' ', '') @register.tag(name='blockmedia') def blockmedia(parser, token): try: tagname = token.split_contents() except ValueError: raise template.TemplateSyntaxError("blockmedia tag does not use arguments") nodelist = [] while True: nodelist.append(parser.parse(('endblockmedia'))) next = parser.next_token() if next.contents == 'endblockmedia': break return BlockMediaUrlNode(nodelist) @register.simple_tag def fullmedia(url): domain = settings.APP_BASE_URL #protocol = getattr(settings, "PROTOCOL", "http") path = media(url) return "%s%s" % (domain, path) class SimpleVarNode(template.Node): def __init__(self, name, value): self.name = name self.value = template.Variable(value) def render(self, context): context[self.name] = self.value.resolve(context) return '' class BlockVarNode(template.Node): def
(self, name, block): self.name = name self.block = block def render(self, context): source = self.block.render(context) context[self.name] = source.strip() return '' @register.tag(name='var') def do_var(parser, token): tokens = token.split_contents()[1:] if not len(tokens) or not re.match('^\w+$', tokens[0]): raise template.TemplateSyntaxError("Expected variable name") if len(tokens) == 1: nodelist = parser.parse(('endvar',)) parser.delete_first_token() return BlockVarNode(tokens[0], nodelist) elif len(tokens) == 3: return SimpleVarNode(tokens[0], tokens[2]) raise template.TemplateSyntaxError("Invalid number of arguments") class DeclareNode(template.Node): dec_re = re.compile('^\s*(\w+)\s*(:?=)\s*(.*)$') def __init__(self, block): self.block = block def render(self, context): source = self.block.render(context) for line in source.splitlines(): m = self.dec_re.search(line) if m: clist = list(context) clist.reverse() d = {} d['_'] = _ d['os'] = os d['html'] = html d['reverse'] = reverse for c in clist: d.update(c) try: context[m.group(1).strip()] = eval(m.group(3).strip(), d) except Exception, e: logging.error("Error in declare tag, when evaluating: %s" % m.group(3).strip()) raise return '' @register.tag(name='declare') def do_declare(parser, token): nodelist = parser.parse(('enddeclare',)) parser.delete_first_token() return DeclareNode(nodelist)
__init__
identifier_name
extra_tags.py
import time import os import posixpath import datetime import math import re import logging from django import template from django.utils.encoding import smart_unicode from django.utils.safestring import mark_safe from forum.models import Question, Answer, QuestionRevision, AnswerRevision, NodeRevision from django.utils.translation import ugettext as _ from django.utils.translation import ungettext from django.utils import simplejson from forum import settings from django.template.defaulttags import url as default_url from forum import skins from forum.utils import html from extra_filters import decorated_int from django.core.urlresolvers import reverse register = template.Library() GRAVATAR_TEMPLATE = ('<img class="gravatar" width="%(size)s" height="%(size)s" ' 'src="http://www.gravatar.com/avatar/%(gravatar_hash)s' '?s=%(size)s&amp;d=%(default)s&amp;r=%(rating)s" ' 'alt="%(username)s\'s gravatar image" />') @register.simple_tag def gravatar(user, size): try: gravatar = user['gravatar'] username = user['username'] except (TypeError, AttributeError, KeyError): gravatar = user.gravatar username = user.username return mark_safe(GRAVATAR_TEMPLATE % { 'size': size, 'gravatar_hash': gravatar, 'default': settings.GRAVATAR_DEFAULT_IMAGE, 'rating': settings.GRAVATAR_ALLOWED_RATING, 'username': template.defaultfilters.urlencode(username), }) @register.simple_tag def get_score_badge(user): if user.is_suspended(): return _("(suspended)") repstr = decorated_int(user.reputation, "") BADGE_TEMPLATE = '<span class="score" title="%(reputation)s %(reputationword)s">%(repstr)s</span>' if user.gold > 0 : BADGE_TEMPLATE = '%s%s' % (BADGE_TEMPLATE, '<span title="%(gold)s %(badgesword)s">' '<span class="badge1">&#9679;</span>' '<span class="badgecount">%(gold)s</span>' '</span>') if user.silver > 0: BADGE_TEMPLATE = '%s%s' % (BADGE_TEMPLATE, '<span title="%(silver)s %(badgesword)s">' '<span class="silver">&#9679;</span>' '<span class="badgecount">%(silver)s</span>' '</span>') if user.bronze > 0: BADGE_TEMPLATE = '%s%s' % (BADGE_TEMPLATE, '<span title="%(bronze)s %(badgesword)s">' '<span class="bronze">&#9679;</span>' '<span class="badgecount">%(bronze)s</span>' '</span>') BADGE_TEMPLATE = smart_unicode(BADGE_TEMPLATE, encoding='utf-8', strings_only=False, errors='strict') return mark_safe(BADGE_TEMPLATE % { 'reputation' : user.reputation, 'repstr': repstr, 'gold' : user.gold, 'silver' : user.silver, 'bronze' : user.bronze, 'badgesword' : _('badges'), 'reputationword' : _('reputation points'), }) @register.simple_tag def get_age(birthday): current_time = datetime.datetime(*time.localtime()[0:6]) year = birthday.year month = birthday.month day = birthday.day diff = current_time - datetime.datetime(year, month, day, 0, 0, 0) return diff.days / 365 @register.simple_tag def diff_date(date, limen=2): if not date: return _('unknown') now = datetime.datetime.now() diff = now - date days = diff.days hours = int(diff.seconds/3600) minutes = int(diff.seconds/60) if days > 2: if date.year == now.year: return date.strftime(_("%b %d at %H:%M").encode()) else: return date.strftime(_("%b %d '%y at %H:%M").encode()) elif days == 2: return _('2 days ago') elif days == 1: return _('yesterday') elif minutes >= 60: return ungettext('%(hr)d ' + _("hour ago"), '%(hr)d ' + _("hours ago"), hours) % {'hr':hours} elif diff.seconds >= 60: return ungettext('%(min)d ' + _("min ago"), '%(min)d ' + _("mins ago"), minutes) % {'min':minutes} else: return ungettext('%(sec)d ' + _("sec ago"), '%(sec)d ' + _("secs ago"), diff.seconds) % {'sec':diff.seconds} @register.simple_tag def media(url): url = skins.find_media_source(url) if url: # Create the URL prefix. url_prefix = settings.FORCE_SCRIPT_NAME + '/m/' # Make sure any duplicate forward slashes are replaced with a single # forward slash. url_prefix = re.sub("/+", "/", url_prefix) url = url_prefix + url return url class ItemSeparatorNode(template.Node): def __init__(self, separator): sep = separator.strip() if sep[0] == sep[-1] and sep[0] in ('\'', '"'): sep = sep[1:-1] else:
self.content = sep def render(self, context): return self.content class BlockMediaUrlNode(template.Node): def __init__(self, nodelist): self.items = nodelist def render(self, context): prefix = settings.APP_URL + 'm/' url = '' if self.items: url += '/' for item in self.items: url += item.render(context) url = skins.find_media_source(url) url = prefix + url out = url return out.replace(' ', '') @register.tag(name='blockmedia') def blockmedia(parser, token): try: tagname = token.split_contents() except ValueError: raise template.TemplateSyntaxError("blockmedia tag does not use arguments") nodelist = [] while True: nodelist.append(parser.parse(('endblockmedia'))) next = parser.next_token() if next.contents == 'endblockmedia': break return BlockMediaUrlNode(nodelist) @register.simple_tag def fullmedia(url): domain = settings.APP_BASE_URL #protocol = getattr(settings, "PROTOCOL", "http") path = media(url) return "%s%s" % (domain, path) class SimpleVarNode(template.Node): def __init__(self, name, value): self.name = name self.value = template.Variable(value) def render(self, context): context[self.name] = self.value.resolve(context) return '' class BlockVarNode(template.Node): def __init__(self, name, block): self.name = name self.block = block def render(self, context): source = self.block.render(context) context[self.name] = source.strip() return '' @register.tag(name='var') def do_var(parser, token): tokens = token.split_contents()[1:] if not len(tokens) or not re.match('^\w+$', tokens[0]): raise template.TemplateSyntaxError("Expected variable name") if len(tokens) == 1: nodelist = parser.parse(('endvar',)) parser.delete_first_token() return BlockVarNode(tokens[0], nodelist) elif len(tokens) == 3: return SimpleVarNode(tokens[0], tokens[2]) raise template.TemplateSyntaxError("Invalid number of arguments") class DeclareNode(template.Node): dec_re = re.compile('^\s*(\w+)\s*(:?=)\s*(.*)$') def __init__(self, block): self.block = block def render(self, context): source = self.block.render(context) for line in source.splitlines(): m = self.dec_re.search(line) if m: clist = list(context) clist.reverse() d = {} d['_'] = _ d['os'] = os d['html'] = html d['reverse'] = reverse for c in clist: d.update(c) try: context[m.group(1).strip()] = eval(m.group(3).strip(), d) except Exception, e: logging.error("Error in declare tag, when evaluating: %s" % m.group(3).strip()) raise return '' @register.tag(name='declare') def do_declare(parser, token): nodelist = parser.parse(('enddeclare',)) parser.delete_first_token() return DeclareNode(nodelist)
raise template.TemplateSyntaxError('separator in joinitems tag must be quoted')
conditional_block
extra_tags.py
import time import os import posixpath import datetime import math import re import logging from django import template from django.utils.encoding import smart_unicode from django.utils.safestring import mark_safe from forum.models import Question, Answer, QuestionRevision, AnswerRevision, NodeRevision from django.utils.translation import ugettext as _ from django.utils.translation import ungettext from django.utils import simplejson from forum import settings from django.template.defaulttags import url as default_url from forum import skins from forum.utils import html from extra_filters import decorated_int from django.core.urlresolvers import reverse register = template.Library() GRAVATAR_TEMPLATE = ('<img class="gravatar" width="%(size)s" height="%(size)s" ' 'src="http://www.gravatar.com/avatar/%(gravatar_hash)s' '?s=%(size)s&amp;d=%(default)s&amp;r=%(rating)s" ' 'alt="%(username)s\'s gravatar image" />') @register.simple_tag def gravatar(user, size): try: gravatar = user['gravatar'] username = user['username'] except (TypeError, AttributeError, KeyError): gravatar = user.gravatar username = user.username return mark_safe(GRAVATAR_TEMPLATE % { 'size': size, 'gravatar_hash': gravatar, 'default': settings.GRAVATAR_DEFAULT_IMAGE, 'rating': settings.GRAVATAR_ALLOWED_RATING, 'username': template.defaultfilters.urlencode(username), }) @register.simple_tag def get_score_badge(user): if user.is_suspended(): return _("(suspended)") repstr = decorated_int(user.reputation, "") BADGE_TEMPLATE = '<span class="score" title="%(reputation)s %(reputationword)s">%(repstr)s</span>' if user.gold > 0 : BADGE_TEMPLATE = '%s%s' % (BADGE_TEMPLATE, '<span title="%(gold)s %(badgesword)s">' '<span class="badge1">&#9679;</span>' '<span class="badgecount">%(gold)s</span>' '</span>') if user.silver > 0: BADGE_TEMPLATE = '%s%s' % (BADGE_TEMPLATE, '<span title="%(silver)s %(badgesword)s">' '<span class="silver">&#9679;</span>' '<span class="badgecount">%(silver)s</span>' '</span>') if user.bronze > 0: BADGE_TEMPLATE = '%s%s' % (BADGE_TEMPLATE, '<span title="%(bronze)s %(badgesword)s">' '<span class="bronze">&#9679;</span>' '<span class="badgecount">%(bronze)s</span>' '</span>') BADGE_TEMPLATE = smart_unicode(BADGE_TEMPLATE, encoding='utf-8', strings_only=False, errors='strict') return mark_safe(BADGE_TEMPLATE % { 'reputation' : user.reputation, 'repstr': repstr, 'gold' : user.gold, 'silver' : user.silver, 'bronze' : user.bronze, 'badgesword' : _('badges'), 'reputationword' : _('reputation points'), }) @register.simple_tag def get_age(birthday): current_time = datetime.datetime(*time.localtime()[0:6]) year = birthday.year month = birthday.month day = birthday.day diff = current_time - datetime.datetime(year, month, day, 0, 0, 0) return diff.days / 365 @register.simple_tag def diff_date(date, limen=2): if not date: return _('unknown') now = datetime.datetime.now() diff = now - date days = diff.days hours = int(diff.seconds/3600) minutes = int(diff.seconds/60) if days > 2: if date.year == now.year: return date.strftime(_("%b %d at %H:%M").encode()) else: return date.strftime(_("%b %d '%y at %H:%M").encode()) elif days == 2: return _('2 days ago') elif days == 1: return _('yesterday') elif minutes >= 60: return ungettext('%(hr)d ' + _("hour ago"), '%(hr)d ' + _("hours ago"), hours) % {'hr':hours} elif diff.seconds >= 60: return ungettext('%(min)d ' + _("min ago"), '%(min)d ' + _("mins ago"), minutes) % {'min':minutes} else: return ungettext('%(sec)d ' + _("sec ago"), '%(sec)d ' + _("secs ago"), diff.seconds) % {'sec':diff.seconds} @register.simple_tag def media(url): url = skins.find_media_source(url) if url: # Create the URL prefix. url_prefix = settings.FORCE_SCRIPT_NAME + '/m/' # Make sure any duplicate forward slashes are replaced with a single # forward slash. url_prefix = re.sub("/+", "/", url_prefix) url = url_prefix + url return url class ItemSeparatorNode(template.Node): def __init__(self, separator): sep = separator.strip() if sep[0] == sep[-1] and sep[0] in ('\'', '"'): sep = sep[1:-1] else: raise template.TemplateSyntaxError('separator in joinitems tag must be quoted') self.content = sep def render(self, context): return self.content class BlockMediaUrlNode(template.Node): def __init__(self, nodelist): self.items = nodelist def render(self, context): prefix = settings.APP_URL + 'm/' url = '' if self.items: url += '/' for item in self.items: url += item.render(context) url = skins.find_media_source(url) url = prefix + url out = url return out.replace(' ', '') @register.tag(name='blockmedia') def blockmedia(parser, token): try: tagname = token.split_contents() except ValueError: raise template.TemplateSyntaxError("blockmedia tag does not use arguments") nodelist = [] while True: nodelist.append(parser.parse(('endblockmedia'))) next = parser.next_token() if next.contents == 'endblockmedia': break return BlockMediaUrlNode(nodelist) @register.simple_tag def fullmedia(url): domain = settings.APP_BASE_URL #protocol = getattr(settings, "PROTOCOL", "http") path = media(url) return "%s%s" % (domain, path) class SimpleVarNode(template.Node): def __init__(self, name, value): self.name = name self.value = template.Variable(value) def render(self, context): context[self.name] = self.value.resolve(context) return '' class BlockVarNode(template.Node): def __init__(self, name, block): self.name = name self.block = block def render(self, context): source = self.block.render(context) context[self.name] = source.strip() return '' @register.tag(name='var') def do_var(parser, token): tokens = token.split_contents()[1:]
raise template.TemplateSyntaxError("Expected variable name") if len(tokens) == 1: nodelist = parser.parse(('endvar',)) parser.delete_first_token() return BlockVarNode(tokens[0], nodelist) elif len(tokens) == 3: return SimpleVarNode(tokens[0], tokens[2]) raise template.TemplateSyntaxError("Invalid number of arguments") class DeclareNode(template.Node): dec_re = re.compile('^\s*(\w+)\s*(:?=)\s*(.*)$') def __init__(self, block): self.block = block def render(self, context): source = self.block.render(context) for line in source.splitlines(): m = self.dec_re.search(line) if m: clist = list(context) clist.reverse() d = {} d['_'] = _ d['os'] = os d['html'] = html d['reverse'] = reverse for c in clist: d.update(c) try: context[m.group(1).strip()] = eval(m.group(3).strip(), d) except Exception, e: logging.error("Error in declare tag, when evaluating: %s" % m.group(3).strip()) raise return '' @register.tag(name='declare') def do_declare(parser, token): nodelist = parser.parse(('enddeclare',)) parser.delete_first_token() return DeclareNode(nodelist)
if not len(tokens) or not re.match('^\w+$', tokens[0]):
random_line_split
logical_spec.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 {LogicalFileSystem, LogicalProjectPath} from '../src/logical'; import {AbsoluteFsPath} from '../src/types'; describe('logical paths', () => { describe('LogicalFileSystem', () => { it('should determine logical paths in a single root file system', () => { const fs = new LogicalFileSystem([abs('/test')]); expect(fs.logicalPathOfFile(abs('/test/foo/foo.ts'))) .toEqual('/foo/foo' as LogicalProjectPath); expect(fs.logicalPathOfFile(abs('/test/bar/bar.ts'))) .toEqual('/bar/bar' as LogicalProjectPath); expect(fs.logicalPathOfFile(abs('/not-test/bar.ts'))).toBeNull(); }); it('should determine logical paths in a multi-root file system', () => { const fs = new LogicalFileSystem([abs('/test/foo'), abs('/test/bar')]); expect(fs.logicalPathOfFile(abs('/test/foo/foo.ts'))).toEqual('/foo' as LogicalProjectPath); expect(fs.logicalPathOfFile(abs('/test/bar/bar.ts'))).toEqual('/bar' as LogicalProjectPath); }); it('should continue to work when one root is a child of another', () => { const fs = new LogicalFileSystem([abs('/test'), abs('/test/dist')]); expect(fs.logicalPathOfFile(abs('/test/foo.ts'))).toEqual('/foo' as LogicalProjectPath); expect(fs.logicalPathOfFile(abs('/test/dist/foo.ts'))).toEqual('/foo' as LogicalProjectPath); }); it('should always return `/` prefixed logical paths', () => { const rootFs = new LogicalFileSystem([abs('/')]); expect(rootFs.logicalPathOfFile(abs('/foo/foo.ts'))) .toEqual('/foo/foo' as LogicalProjectPath); const nonRootFs = new LogicalFileSystem([abs('/test/')]); expect(nonRootFs.logicalPathOfFile(abs('/test/foo/foo.ts'))) .toEqual('/foo/foo' as LogicalProjectPath); }); }); describe('utilities', () => { it('should give a relative path between two adjacent logical files', () => { const res = LogicalProjectPath.relativePathBetween( '/foo' as LogicalProjectPath, '/bar' as LogicalProjectPath); expect(res).toEqual('./bar'); }); it('should give a relative path between two non-adjacent logical files', () => { const res = LogicalProjectPath.relativePathBetween( '/foo/index' as LogicalProjectPath, '/bar/index' as LogicalProjectPath); expect(res).toEqual('../bar/index'); }); }); }); function
(file: string): AbsoluteFsPath { return AbsoluteFsPath.from(file); }
abs
identifier_name
logical_spec.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 {LogicalFileSystem, LogicalProjectPath} from '../src/logical'; import {AbsoluteFsPath} from '../src/types'; describe('logical paths', () => { describe('LogicalFileSystem', () => { it('should determine logical paths in a single root file system', () => { const fs = new LogicalFileSystem([abs('/test')]); expect(fs.logicalPathOfFile(abs('/test/foo/foo.ts'))) .toEqual('/foo/foo' as LogicalProjectPath); expect(fs.logicalPathOfFile(abs('/test/bar/bar.ts')))
it('should determine logical paths in a multi-root file system', () => { const fs = new LogicalFileSystem([abs('/test/foo'), abs('/test/bar')]); expect(fs.logicalPathOfFile(abs('/test/foo/foo.ts'))).toEqual('/foo' as LogicalProjectPath); expect(fs.logicalPathOfFile(abs('/test/bar/bar.ts'))).toEqual('/bar' as LogicalProjectPath); }); it('should continue to work when one root is a child of another', () => { const fs = new LogicalFileSystem([abs('/test'), abs('/test/dist')]); expect(fs.logicalPathOfFile(abs('/test/foo.ts'))).toEqual('/foo' as LogicalProjectPath); expect(fs.logicalPathOfFile(abs('/test/dist/foo.ts'))).toEqual('/foo' as LogicalProjectPath); }); it('should always return `/` prefixed logical paths', () => { const rootFs = new LogicalFileSystem([abs('/')]); expect(rootFs.logicalPathOfFile(abs('/foo/foo.ts'))) .toEqual('/foo/foo' as LogicalProjectPath); const nonRootFs = new LogicalFileSystem([abs('/test/')]); expect(nonRootFs.logicalPathOfFile(abs('/test/foo/foo.ts'))) .toEqual('/foo/foo' as LogicalProjectPath); }); }); describe('utilities', () => { it('should give a relative path between two adjacent logical files', () => { const res = LogicalProjectPath.relativePathBetween( '/foo' as LogicalProjectPath, '/bar' as LogicalProjectPath); expect(res).toEqual('./bar'); }); it('should give a relative path between two non-adjacent logical files', () => { const res = LogicalProjectPath.relativePathBetween( '/foo/index' as LogicalProjectPath, '/bar/index' as LogicalProjectPath); expect(res).toEqual('../bar/index'); }); }); }); function abs(file: string): AbsoluteFsPath { return AbsoluteFsPath.from(file); }
.toEqual('/bar/bar' as LogicalProjectPath); expect(fs.logicalPathOfFile(abs('/not-test/bar.ts'))).toBeNull(); });
random_line_split
logical_spec.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 {LogicalFileSystem, LogicalProjectPath} from '../src/logical'; import {AbsoluteFsPath} from '../src/types'; describe('logical paths', () => { describe('LogicalFileSystem', () => { it('should determine logical paths in a single root file system', () => { const fs = new LogicalFileSystem([abs('/test')]); expect(fs.logicalPathOfFile(abs('/test/foo/foo.ts'))) .toEqual('/foo/foo' as LogicalProjectPath); expect(fs.logicalPathOfFile(abs('/test/bar/bar.ts'))) .toEqual('/bar/bar' as LogicalProjectPath); expect(fs.logicalPathOfFile(abs('/not-test/bar.ts'))).toBeNull(); }); it('should determine logical paths in a multi-root file system', () => { const fs = new LogicalFileSystem([abs('/test/foo'), abs('/test/bar')]); expect(fs.logicalPathOfFile(abs('/test/foo/foo.ts'))).toEqual('/foo' as LogicalProjectPath); expect(fs.logicalPathOfFile(abs('/test/bar/bar.ts'))).toEqual('/bar' as LogicalProjectPath); }); it('should continue to work when one root is a child of another', () => { const fs = new LogicalFileSystem([abs('/test'), abs('/test/dist')]); expect(fs.logicalPathOfFile(abs('/test/foo.ts'))).toEqual('/foo' as LogicalProjectPath); expect(fs.logicalPathOfFile(abs('/test/dist/foo.ts'))).toEqual('/foo' as LogicalProjectPath); }); it('should always return `/` prefixed logical paths', () => { const rootFs = new LogicalFileSystem([abs('/')]); expect(rootFs.logicalPathOfFile(abs('/foo/foo.ts'))) .toEqual('/foo/foo' as LogicalProjectPath); const nonRootFs = new LogicalFileSystem([abs('/test/')]); expect(nonRootFs.logicalPathOfFile(abs('/test/foo/foo.ts'))) .toEqual('/foo/foo' as LogicalProjectPath); }); }); describe('utilities', () => { it('should give a relative path between two adjacent logical files', () => { const res = LogicalProjectPath.relativePathBetween( '/foo' as LogicalProjectPath, '/bar' as LogicalProjectPath); expect(res).toEqual('./bar'); }); it('should give a relative path between two non-adjacent logical files', () => { const res = LogicalProjectPath.relativePathBetween( '/foo/index' as LogicalProjectPath, '/bar/index' as LogicalProjectPath); expect(res).toEqual('../bar/index'); }); }); }); function abs(file: string): AbsoluteFsPath
{ return AbsoluteFsPath.from(file); }
identifier_body
tournament.py
# coding: utf-8 # license: GPLv3 from enemies import * from hero import * def annoying_input_int(message =''): answer = None while answer == None: try: answer = int(input(message)) except ValueError: print('Вы ввели недопустимые символы') return answer def game_tournament(hero, dragon_list): for dragon in dragon_list: print('Вышел', dragon._color, 'дракон!') while dragon.is_alive() and hero.is_alive(): print('Вопрос:', dragon.question()) answer = annoying_input_int('Ответ:') if dragon.check_answer(answer): hero.attack(dragon) print('Верно! \n** дракон кричит от боли **') else: dragon.attack(hero) print('Ошибка! \n** вам нанесён удар... **') if dragon.is_alive(): break print('Дракон', dragon._color, 'повержен!\n') if hero.is_alive(): print('Поздравляем! Вы победили!') print('Ваш накопленный опыт:', hero._experience) else: print('К сожалению, Вы проиграли...') def start_game(): try: print('Добро пожаловать в арифметико-ролевую игру с драконами!') print('Представьтесь, пожалуйста: ', end = '') hero = Hero(input())
dragon_number = 3 dragon_list = generate_dragon_list(dragon_number) assert(len(dragon_list) == 3) print('У Вас на пути', dragon_number, 'драконов!') game_tournament(hero, dragon_list) except EOFError: print('Поток ввода закончился. Извините, принимать ответы более невозможно.')
identifier_body
tournament.py
# coding: utf-8 # license: GPLv3 from enemies import * from hero import * def annoying_input_int(message =''): answer = None while answer == None: try: answer = int(input(message)) except ValueError:
print('Вы ввели недопустимые символы') return answer def game_tournament(hero, dragon_list): for dragon in dragon_list: print('Вышел', dragon._color, 'дракон!') while dragon.is_alive() and hero.is_alive(): print('Вопрос:', dragon.question()) answer = annoying_input_int('Ответ:') if dragon.check_answer(answer): hero.attack(dragon) print('Верно! \n** дракон кричит от боли **') else: dragon.attack(hero) print('Ошибка! \n** вам нанесён удар... **') if dragon.is_alive(): break print('Дракон', dragon._color, 'повержен!\n') if hero.is_alive(): print('Поздравляем! Вы победили!') print('Ваш накопленный опыт:', hero._experience) else: print('К сожалению, Вы проиграли...') def start_game(): try: print('Добро пожаловать в арифметико-ролевую игру с драконами!') print('Представьтесь, пожалуйста: ', end = '') hero = Hero(input()) dragon_number = 3 dragon_list = generate_dragon_list(dragon_number) assert(len(dragon_list) == 3) print('У Вас на пути', dragon_number, 'драконов!') game_tournament(hero, dragon_list) except EOFError: print('Поток ввода закончился. Извините, принимать ответы более невозможно.')
random_line_split
tournament.py
# coding: utf-8 # license: GPLv3 from enemies import * from hero import * def annoying_input_int(message =''): answer = None while answer == None: try: answer = int(input(message)) except ValueError: print('Вы ввели недопустимые символы') return answer def game_tournament(hero, dragon_list): for dragon in dragon_list: print('Вышел', dragon._color, 'дракон!') while dragon.is_alive() and hero.is_alive(): print('Вопрос:', dragon.question()) answer = annoying_input_int('Ответ:') if dragon.check_answer(answer): hero.attack(dragon) print('Верно! \n** дракон кричит от боли **') else: dragon.attack(hero) print('Ошибка! \n** вам нанесён удар... **') if dragon.is_alive(): break print('Дракон', dragon._color, 'повержен!\n') if hero.is_alive(): print('Поздравляем! Вы победили!') print('Ваш накопленный опыт:', hero._experience) else:
с драконами!') print('Представьтесь, пожалуйста: ', end = '') hero = Hero(input()) dragon_number = 3 dragon_list = generate_dragon_list(dragon_number) assert(len(dragon_list) == 3) print('У Вас на пути', dragon_number, 'драконов!') game_tournament(hero, dragon_list) except EOFError: print('Поток ввода закончился. Извините, принимать ответы более невозможно.')
print('К сожалению, Вы проиграли...') def start_game(): try: print('Добро пожаловать в арифметико-ролевую игру
conditional_block
tournament.py
# coding: utf-8 # license: GPLv3 from enemies import * from hero import * def annoying_input_int(message =''): answer = None while answer == None: try: answer = int(input(message)) except ValueError: print('Вы ввели недопустимые символы') return answer def game_tournament(hero, drag
or dragon in dragon_list: print('Вышел', dragon._color, 'дракон!') while dragon.is_alive() and hero.is_alive(): print('Вопрос:', dragon.question()) answer = annoying_input_int('Ответ:') if dragon.check_answer(answer): hero.attack(dragon) print('Верно! \n** дракон кричит от боли **') else: dragon.attack(hero) print('Ошибка! \n** вам нанесён удар... **') if dragon.is_alive(): break print('Дракон', dragon._color, 'повержен!\n') if hero.is_alive(): print('Поздравляем! Вы победили!') print('Ваш накопленный опыт:', hero._experience) else: print('К сожалению, Вы проиграли...') def start_game(): try: print('Добро пожаловать в арифметико-ролевую игру с драконами!') print('Представьтесь, пожалуйста: ', end = '') hero = Hero(input()) dragon_number = 3 dragon_list = generate_dragon_list(dragon_number) assert(len(dragon_list) == 3) print('У Вас на пути', dragon_number, 'драконов!') game_tournament(hero, dragon_list) except EOFError: print('Поток ввода закончился. Извините, принимать ответы более невозможно.')
on_list): f
identifier_name
MCEImageBrowserDialog.js
class InsertImageDialog extends ConfirmMessageDialog {
* * @type {MessageDialog} */ this.parent = null; this.icon_enabled = false; this.itemClass = "MCEImagesBean"; } setImageID(imageID) { this.imageID = imageID; } setParent(dialog) { this.parent = dialog; } setContents(contents) { this.contents = contents; this.setText(this.contents); } buttonAction(action) { if (action == "confirm") { this.confirm(); } else if (action == "cancel") { this.remove(); } } confirm() { let image_url = new URL(STORAGE_LOCAL, location.href); image_url.searchParams.set("cmd", "image"); image_url.searchParams.set("class", this.itemClass); image_url.searchParams.set("id", this.imageID); let form = this.modal_pane.popup.find("FORM"); let render_mode = form.find("[name='render_mode']").val(); let caption = form.find("[name='caption']").val(); let enable_popup = form.find("[name='enable_popup']"); let width = parseInt(form.find("[name='width']").val()); let height = parseInt(form.find("[name='height']").val()); if (isNaN(width) || width < 1) { width = -1; } if (isNaN(height) || height < 1) { height = -1; } if (width < 1 && height < 1) { showAlert("One of width or height should be positive number"); return; } let image_tag = $("<img>"); if (render_mode == "fit_prc") { if (width>0) { image_tag.attr("width", "" + width + "%"); } if (height>0) { image_tag.attr("height", "" + height + "%"); } } else if (render_mode == "fit_px") { image_url.searchParams.set("width", width); image_url.searchParams.set("height", height); } image_tag.attr("src", image_url.href); image_tag.attr("alt", caption); let final_tag = image_tag; if (enable_popup.is(":checked")) { console.log("Enabling popup"); final_tag = $("<a href='#'></a>"); final_tag.attr("class", "ImagePopup"); final_tag.attr("itemID", this.imageID); final_tag.attr("itemClass", this.itemClass); final_tag.attr("title", caption); final_tag.html(image_tag); } console.log("Inserting into MCE: " + final_tag.get(0).outerHTML); this.parent.mce_textarea.editor.execCommand("mceInsertContent", false, final_tag.get(0).outerHTML); this.remove(); this.parent.remove(); } show() { super.show(); this.modal_pane.popup.find(".preview IMG").on("load", function (event) { this.modal_pane.centerContents(); }.bind(this)); } } class MCEImageBrowserDialog extends JSONDialog { constructor() { super(); this.setID("mceImage_browser"); this.mce_textarea = null; this.field_name = null; this.req.setResponder("mceImage"); this.insert_image = new InsertImageDialog(); this.insert_image.setCaption("Insert Image"); this.insert_image.setParent(this); } setMCETextArea(textarea) { this.mce_textarea = textarea; } buttonAction(action, dialog) { this.remove(); } processResult(responder, funct, result) { let jsonResult = result.json_result; let message = jsonResult.message; let imageID = this.req.getParameter("imageID"); if (funct == "renderDimensionDialog") { this.insert_image.setContents(jsonResult.contents); this.insert_image.setImageID(this.req.getParameter("imageID")); this.insert_image.show(); } else if (funct == "remove") { let element = this.modal_pane.popup.find(".ImageStorage .Collection .Element[imageID='" + imageID + "']"); element.remove(); this.modal_pane.centerContents(); } else if (funct == "find") { const dialog = this; for (var a = 0; a < jsonResult.result_count; a++) { var image = jsonResult.objects[a]; this.modal_pane.popup.find(".ImageStorage .Collection").first().append(image.html); } this.modal_pane.popup.find(".ImageStorage .Collection .Element").each(function (index) { let imageID = $(this).attr("imageID"); $(this).on("click", function (event) { dialog.onClickImage(imageID, event); return false; }); let remove_button = $(this).children(".remove_button").first(); remove_button.on("click", function (event) { dialog.removeImage(imageID, event); return false; }); }); //each image } //find } show() { super.show(); //subsequent shows need clear parameters this.req.clearParameters(); var field = this.modal_pane.popup.find(".SessionUpload").first(); this.field_name = field.attr("field"); this.req.setParameter("field_name", this.field_name); var upload_control = field.data("upload_control"); upload_control.processResult = this.processUploadResult.bind(this); this.loadImages(); //setTimeout(this.loadImages.bind(this), 100); } /** * Handle new image upload to collection * @param result */ processUploadResult(result) { for (var a = 0; a < result.result_count; a++) { var image = result.objects[a]; var imageID = image.imageID; //load the image into the view this.loadImages(imageID); } } loadImages(imageID) { this.req.setFunction("find"); this.req.removeParameter("imageID"); if (imageID > 0) { this.req.setParameter("imageID", imageID); } else { this.modal_pane.popup.find(".ImageStorage .Collection").first().empty(); } this.req.start(); } onClickImage(imageID, event) { this.req.setFunction("renderDimensionDialog"); this.req.setParameter("imageID", imageID); this.req.start(); } removeImage(imageID, event) { this.req.setFunction("remove"); this.req.setParameter("imageID", imageID); this.req.start(); } }
constructor() { super(); this.contents = ""; /**
random_line_split
MCEImageBrowserDialog.js
class InsertImageDialog extends ConfirmMessageDialog { constructor() { super(); this.contents = ""; /** * * @type {MessageDialog} */ this.parent = null; this.icon_enabled = false; this.itemClass = "MCEImagesBean"; } setImageID(imageID) { this.imageID = imageID; } setParent(dialog) { this.parent = dialog; } setContents(contents) { this.contents = contents; this.setText(this.contents); } buttonAction(action) { if (action == "confirm") { this.confirm(); } else if (action == "cancel") { this.remove(); } } confirm() { let image_url = new URL(STORAGE_LOCAL, location.href); image_url.searchParams.set("cmd", "image"); image_url.searchParams.set("class", this.itemClass); image_url.searchParams.set("id", this.imageID); let form = this.modal_pane.popup.find("FORM"); let render_mode = form.find("[name='render_mode']").val(); let caption = form.find("[name='caption']").val(); let enable_popup = form.find("[name='enable_popup']"); let width = parseInt(form.find("[name='width']").val()); let height = parseInt(form.find("[name='height']").val()); if (isNaN(width) || width < 1) { width = -1; } if (isNaN(height) || height < 1) { height = -1; } if (width < 1 && height < 1) { showAlert("One of width or height should be positive number"); return; } let image_tag = $("<img>"); if (render_mode == "fit_prc") { if (width>0) { image_tag.attr("width", "" + width + "%"); } if (height>0) { image_tag.attr("height", "" + height + "%"); } } else if (render_mode == "fit_px") { image_url.searchParams.set("width", width); image_url.searchParams.set("height", height); } image_tag.attr("src", image_url.href); image_tag.attr("alt", caption); let final_tag = image_tag; if (enable_popup.is(":checked")) { console.log("Enabling popup"); final_tag = $("<a href='#'></a>"); final_tag.attr("class", "ImagePopup"); final_tag.attr("itemID", this.imageID); final_tag.attr("itemClass", this.itemClass); final_tag.attr("title", caption); final_tag.html(image_tag); } console.log("Inserting into MCE: " + final_tag.get(0).outerHTML); this.parent.mce_textarea.editor.execCommand("mceInsertContent", false, final_tag.get(0).outerHTML); this.remove(); this.parent.remove(); } show() { super.show(); this.modal_pane.popup.find(".preview IMG").on("load", function (event) { this.modal_pane.centerContents(); }.bind(this)); } } class MCEImageBrowserDialog extends JSONDialog { constructor() { super(); this.setID("mceImage_browser"); this.mce_textarea = null; this.field_name = null; this.req.setResponder("mceImage"); this.insert_image = new InsertImageDialog(); this.insert_image.setCaption("Insert Image"); this.insert_image.setParent(this); } setMCETextArea(textarea) { this.mce_textarea = textarea; } buttonAction(action, dialog) { this.remove(); } processResult(responder, funct, result) { let jsonResult = result.json_result; let message = jsonResult.message; let imageID = this.req.getParameter("imageID"); if (funct == "renderDimensionDialog") { this.insert_image.setContents(jsonResult.contents); this.insert_image.setImageID(this.req.getParameter("imageID")); this.insert_image.show(); } else if (funct == "remove") { let element = this.modal_pane.popup.find(".ImageStorage .Collection .Element[imageID='" + imageID + "']"); element.remove(); this.modal_pane.centerContents(); } else if (funct == "find") { const dialog = this; for (var a = 0; a < jsonResult.result_count; a++) { var image = jsonResult.objects[a]; this.modal_pane.popup.find(".ImageStorage .Collection").first().append(image.html); } this.modal_pane.popup.find(".ImageStorage .Collection .Element").each(function (index) { let imageID = $(this).attr("imageID"); $(this).on("click", function (event) { dialog.onClickImage(imageID, event); return false; }); let remove_button = $(this).children(".remove_button").first(); remove_button.on("click", function (event) { dialog.removeImage(imageID, event); return false; }); }); //each image } //find } show() { super.show(); //subsequent shows need clear parameters this.req.clearParameters(); var field = this.modal_pane.popup.find(".SessionUpload").first(); this.field_name = field.attr("field"); this.req.setParameter("field_name", this.field_name); var upload_control = field.data("upload_control"); upload_control.processResult = this.processUploadResult.bind(this); this.loadImages(); //setTimeout(this.loadImages.bind(this), 100); } /** * Handle new image upload to collection * @param result */ processUploadResult(result)
loadImages(imageID) { this.req.setFunction("find"); this.req.removeParameter("imageID"); if (imageID > 0) { this.req.setParameter("imageID", imageID); } else { this.modal_pane.popup.find(".ImageStorage .Collection").first().empty(); } this.req.start(); } onClickImage(imageID, event) { this.req.setFunction("renderDimensionDialog"); this.req.setParameter("imageID", imageID); this.req.start(); } removeImage(imageID, event) { this.req.setFunction("remove"); this.req.setParameter("imageID", imageID); this.req.start(); } }
{ for (var a = 0; a < result.result_count; a++) { var image = result.objects[a]; var imageID = image.imageID; //load the image into the view this.loadImages(imageID); } }
identifier_body