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
jcarousel.responsive.js
(function($) { $(function() { var jcarousel = $('.jcarousel'); jcarousel .on('jcarousel:reload jcarousel:create', function () { var width = jcarousel.innerWidth(); if (width >= 600)
else if (width >= 350) { width = width / 2; } jcarousel.jcarousel('items').css('width', width + 'px'); }) .jcarousel({ wrap: 'circular' }); $('.jcarousel-control-prev') .jcarouselControl({ target: '-=1' }); $('.jcarousel-control-next') .jcarouselControl({ target: '+=1' }); $('.jcarousel-pagination') .on('jcarouselpagination:active', 'a', function() { $(this).addClass('active'); }) .on('jcarouselpagination:inactive', 'a', function() { $(this).removeClass('active'); }) .on('click', function(e) { e.preventDefault(); }) .jcarouselPagination({ perPage: 1, item: function(page) { return '<a href="#' + page + '">' + page + '</a>'; } }); }); })(jQuery);
{ width = width / 3; }
conditional_block
jcarousel.responsive.js
(function($) { $(function() { var jcarousel = $('.jcarousel'); jcarousel .on('jcarousel:reload jcarousel:create', function () { var width = jcarousel.innerWidth(); if (width >= 600) { width = width / 3; } else if (width >= 350) { width = width / 2; } jcarousel.jcarousel('items').css('width', width + 'px'); }) .jcarousel({ wrap: 'circular' }); $('.jcarousel-control-prev') .jcarouselControl({ target: '-=1' }); $('.jcarousel-control-next') .jcarouselControl({ target: '+=1' }); $('.jcarousel-pagination') .on('jcarouselpagination:active', 'a', function() { $(this).addClass('active'); }) .on('jcarouselpagination:inactive', 'a', function() { $(this).removeClass('active'); }) .on('click', function(e) { e.preventDefault(); }) .jcarouselPagination({ perPage: 1,
return '<a href="#' + page + '">' + page + '</a>'; } }); }); })(jQuery);
item: function(page) {
random_line_split
login.component.ts
import { Component, OnInit, OnDestroy, ViewEncapsulation } from '@angular/core'; import { Router } from '@angular/router'; import {UserService} from "../../services/user/user.service"; @Component({ selector: 'app-login', templateUrl: './login.component.html', providers: [], styleUrls: ['./login.scss'],
encapsulation: ViewEncapsulation.None }) export class LoginComponent { public view: any = { authenticated: false, email: '', password: '' }; constructor(private router: Router, private userService: UserService) { } login() { // Probably should use an Angular 2 Resolver instead of this constructor logic, but that whole mechanism seems too weighty this.userService.getUsers() .subscribe( users => { // Uncomment the next statement if you want to force routing to /TeamSetup // users.length = 0; if (users.length === 0) { this.router.navigateByUrl('/TeamSetup'); } else { this.router.navigateByUrl('/IdeaFlow'); } }, error => { console.log(error); }); return false; } }
random_line_split
login.component.ts
import { Component, OnInit, OnDestroy, ViewEncapsulation } from '@angular/core'; import { Router } from '@angular/router'; import {UserService} from "../../services/user/user.service"; @Component({ selector: 'app-login', templateUrl: './login.component.html', providers: [], styleUrls: ['./login.scss'], encapsulation: ViewEncapsulation.None }) export class LoginComponent { public view: any = { authenticated: false, email: '', password: '' }; constructor(private router: Router, private userService: UserService) { } login() { // Probably should use an Angular 2 Resolver instead of this constructor logic, but that whole mechanism seems too weighty this.userService.getUsers() .subscribe( users => { // Uncomment the next statement if you want to force routing to /TeamSetup // users.length = 0; if (users.length === 0)
else { this.router.navigateByUrl('/IdeaFlow'); } }, error => { console.log(error); }); return false; } }
{ this.router.navigateByUrl('/TeamSetup'); }
conditional_block
login.component.ts
import { Component, OnInit, OnDestroy, ViewEncapsulation } from '@angular/core'; import { Router } from '@angular/router'; import {UserService} from "../../services/user/user.service"; @Component({ selector: 'app-login', templateUrl: './login.component.html', providers: [], styleUrls: ['./login.scss'], encapsulation: ViewEncapsulation.None }) export class LoginComponent { public view: any = { authenticated: false, email: '', password: '' };
(private router: Router, private userService: UserService) { } login() { // Probably should use an Angular 2 Resolver instead of this constructor logic, but that whole mechanism seems too weighty this.userService.getUsers() .subscribe( users => { // Uncomment the next statement if you want to force routing to /TeamSetup // users.length = 0; if (users.length === 0) { this.router.navigateByUrl('/TeamSetup'); } else { this.router.navigateByUrl('/IdeaFlow'); } }, error => { console.log(error); }); return false; } }
constructor
identifier_name
login.component.ts
import { Component, OnInit, OnDestroy, ViewEncapsulation } from '@angular/core'; import { Router } from '@angular/router'; import {UserService} from "../../services/user/user.service"; @Component({ selector: 'app-login', templateUrl: './login.component.html', providers: [], styleUrls: ['./login.scss'], encapsulation: ViewEncapsulation.None }) export class LoginComponent { public view: any = { authenticated: false, email: '', password: '' }; constructor(private router: Router, private userService: UserService)
login() { // Probably should use an Angular 2 Resolver instead of this constructor logic, but that whole mechanism seems too weighty this.userService.getUsers() .subscribe( users => { // Uncomment the next statement if you want to force routing to /TeamSetup // users.length = 0; if (users.length === 0) { this.router.navigateByUrl('/TeamSetup'); } else { this.router.navigateByUrl('/IdeaFlow'); } }, error => { console.log(error); }); return false; } }
{ }
identifier_body
config.rs
//! Utilities for managing the configuration of the website. //! //! The configuration should contain values that I expect to change. This way, I can edit them all //! in a single human-readable file instead of having to track down the values in the code. use std::fs::File; use std::io::prelude::*; use std::path::Path; use log::*; use serde::Deserialize; use serde_yaml; use url::Url; use url_serde; use crate::errors::*; /// Configuration values for the website. #[derive(Debug, PartialEq, Deserialize)] pub struct Config { /// A link to a PDF copy of my Resume. #[serde(with = "url_serde")] pub resume_link: Url, } fn parse_config<R>(reader: R) -> Result<Config> where R: Read, { let config = serde_yaml::from_reader(reader)?; Ok(config) } /// Load the website configuration from a path. pub fn load<P>(config_path: P) -> Result<Config> where P: AsRef<Path>, { let path = config_path.as_ref().to_str().unwrap(); info!("loading configuration from {}", path); let config_file = File::open(&config_path).chain_err(|| "error opening config file")?; parse_config(config_file) } #[cfg(test)] mod tests { use super::*; use url::Url; #[test] fn load_config()
}
{ let test_config = String::from( r#" --- resume_link: http://google.com "#, ); let expected_config = Config { resume_link: Url::parse("http://google.com").unwrap(), }; assert_eq!( expected_config, super::parse_config(test_config.as_bytes()).unwrap() ); }
identifier_body
config.rs
//! Utilities for managing the configuration of the website. //! //! The configuration should contain values that I expect to change. This way, I can edit them all //! in a single human-readable file instead of having to track down the values in the code. use std::fs::File; use std::io::prelude::*; use std::path::Path; use log::*; use serde::Deserialize; use serde_yaml; use url::Url; use url_serde; use crate::errors::*; /// Configuration values for the website. #[derive(Debug, PartialEq, Deserialize)] pub struct Config { /// A link to a PDF copy of my Resume. #[serde(with = "url_serde")] pub resume_link: Url, } fn parse_config<R>(reader: R) -> Result<Config> where R: Read, { let config = serde_yaml::from_reader(reader)?; Ok(config) } /// Load the website configuration from a path. pub fn load<P>(config_path: P) -> Result<Config> where P: AsRef<Path>, { let path = config_path.as_ref().to_str().unwrap(); info!("loading configuration from {}", path); let config_file = File::open(&config_path).chain_err(|| "error opening config file")?; parse_config(config_file) } #[cfg(test)] mod tests { use super::*; use url::Url; #[test] fn
() { let test_config = String::from( r#" --- resume_link: http://google.com "#, ); let expected_config = Config { resume_link: Url::parse("http://google.com").unwrap(), }; assert_eq!( expected_config, super::parse_config(test_config.as_bytes()).unwrap() ); } }
load_config
identifier_name
config.rs
//! Utilities for managing the configuration of the website. //! //! The configuration should contain values that I expect to change. This way, I can edit them all //! in a single human-readable file instead of having to track down the values in the code. use std::fs::File;
use serde_yaml; use url::Url; use url_serde; use crate::errors::*; /// Configuration values for the website. #[derive(Debug, PartialEq, Deserialize)] pub struct Config { /// A link to a PDF copy of my Resume. #[serde(with = "url_serde")] pub resume_link: Url, } fn parse_config<R>(reader: R) -> Result<Config> where R: Read, { let config = serde_yaml::from_reader(reader)?; Ok(config) } /// Load the website configuration from a path. pub fn load<P>(config_path: P) -> Result<Config> where P: AsRef<Path>, { let path = config_path.as_ref().to_str().unwrap(); info!("loading configuration from {}", path); let config_file = File::open(&config_path).chain_err(|| "error opening config file")?; parse_config(config_file) } #[cfg(test)] mod tests { use super::*; use url::Url; #[test] fn load_config() { let test_config = String::from( r#" --- resume_link: http://google.com "#, ); let expected_config = Config { resume_link: Url::parse("http://google.com").unwrap(), }; assert_eq!( expected_config, super::parse_config(test_config.as_bytes()).unwrap() ); } }
use std::io::prelude::*; use std::path::Path; use log::*; use serde::Deserialize;
random_line_split
authorize-steps.js
/** * Created by moshensky on 6/17/15. */ import {inject} from 'aurelia-dependency-injection'; import {Session} from './session'; import {Logger} from './logger'; import {Locale} from './locale'; import {Config} from './config'; import {Redirect} from 'aurelia-router'; class BaseAuthorizeStep { constructor(session, logger) { this.session = session; this.logger = logger; this.locale = Locale.Repository.default; this.loginRoute = Config.routerAuthStepOpts.loginRoute; } run(navigationInstruction, next) { if (!this.session.isUserLoggedIn() && navigationInstruction.config.route !== this.loginRoute) { this.logger.warn(this.locale.translate('pleaseLogin')); return next.cancel(new Redirect(this.loginRoute)); } let canAccess = this.authorize(navigationInstruction); if (canAccess === false) { this.logger.error(this.locale.translate('notAuthorized')); return next.cancel(); } return next(); } authorize(navigationInstruction) { if (navigationInstruction.parentInstruction === null) { return this.canAccess(navigationInstruction); } else { let canAccess = this.canAccess(navigationInstruction); if (hasRole){ return this.authorize(navigationInstruction.parentInstruction) } else { return false; } } }
() { } } @inject(Session, Logger) export class RolesAuthorizeStep extends BaseAuthorizeStep { constructor(session, logger) { super(session, logger); } canAccess(navigationInstruction) { if (navigationInstruction.config.roles) { return this.session.userHasAtLeastOneRole(navigationInstruction.config.roles); } return true; } } @inject(Session, Logger) export class AccessRightsAuthorizeStep extends BaseAuthorizeStep { constructor(session, logger) { super(session, logger); } canAccess(navigationInstruction) { if (navigationInstruction.config.accessRight) { return this.session.userHasAccessRight(navigationInstruction.config.accessRight); } return true; } }
canAccess
identifier_name
authorize-steps.js
/** * Created by moshensky on 6/17/15. */ import {inject} from 'aurelia-dependency-injection'; import {Session} from './session'; import {Logger} from './logger'; import {Locale} from './locale'; import {Config} from './config'; import {Redirect} from 'aurelia-router'; class BaseAuthorizeStep { constructor(session, logger) { this.session = session; this.logger = logger; this.locale = Locale.Repository.default; this.loginRoute = Config.routerAuthStepOpts.loginRoute; } run(navigationInstruction, next) { if (!this.session.isUserLoggedIn() && navigationInstruction.config.route !== this.loginRoute) { this.logger.warn(this.locale.translate('pleaseLogin')); return next.cancel(new Redirect(this.loginRoute)); } let canAccess = this.authorize(navigationInstruction); if (canAccess === false) { this.logger.error(this.locale.translate('notAuthorized')); return next.cancel(); } return next(); } authorize(navigationInstruction) { if (navigationInstruction.parentInstruction === null) { return this.canAccess(navigationInstruction); } else { let canAccess = this.canAccess(navigationInstruction); if (hasRole){ return this.authorize(navigationInstruction.parentInstruction) } else {
return false; } } } canAccess() { } } @inject(Session, Logger) export class RolesAuthorizeStep extends BaseAuthorizeStep { constructor(session, logger) { super(session, logger); } canAccess(navigationInstruction) { if (navigationInstruction.config.roles) { return this.session.userHasAtLeastOneRole(navigationInstruction.config.roles); } return true; } } @inject(Session, Logger) export class AccessRightsAuthorizeStep extends BaseAuthorizeStep { constructor(session, logger) { super(session, logger); } canAccess(navigationInstruction) { if (navigationInstruction.config.accessRight) { return this.session.userHasAccessRight(navigationInstruction.config.accessRight); } return true; } }
random_line_split
authorize-steps.js
/** * Created by moshensky on 6/17/15. */ import {inject} from 'aurelia-dependency-injection'; import {Session} from './session'; import {Logger} from './logger'; import {Locale} from './locale'; import {Config} from './config'; import {Redirect} from 'aurelia-router'; class BaseAuthorizeStep { constructor(session, logger)
run(navigationInstruction, next) { if (!this.session.isUserLoggedIn() && navigationInstruction.config.route !== this.loginRoute) { this.logger.warn(this.locale.translate('pleaseLogin')); return next.cancel(new Redirect(this.loginRoute)); } let canAccess = this.authorize(navigationInstruction); if (canAccess === false) { this.logger.error(this.locale.translate('notAuthorized')); return next.cancel(); } return next(); } authorize(navigationInstruction) { if (navigationInstruction.parentInstruction === null) { return this.canAccess(navigationInstruction); } else { let canAccess = this.canAccess(navigationInstruction); if (hasRole){ return this.authorize(navigationInstruction.parentInstruction) } else { return false; } } } canAccess() { } } @inject(Session, Logger) export class RolesAuthorizeStep extends BaseAuthorizeStep { constructor(session, logger) { super(session, logger); } canAccess(navigationInstruction) { if (navigationInstruction.config.roles) { return this.session.userHasAtLeastOneRole(navigationInstruction.config.roles); } return true; } } @inject(Session, Logger) export class AccessRightsAuthorizeStep extends BaseAuthorizeStep { constructor(session, logger) { super(session, logger); } canAccess(navigationInstruction) { if (navigationInstruction.config.accessRight) { return this.session.userHasAccessRight(navigationInstruction.config.accessRight); } return true; } }
{ this.session = session; this.logger = logger; this.locale = Locale.Repository.default; this.loginRoute = Config.routerAuthStepOpts.loginRoute; }
identifier_body
authorize-steps.js
/** * Created by moshensky on 6/17/15. */ import {inject} from 'aurelia-dependency-injection'; import {Session} from './session'; import {Logger} from './logger'; import {Locale} from './locale'; import {Config} from './config'; import {Redirect} from 'aurelia-router'; class BaseAuthorizeStep { constructor(session, logger) { this.session = session; this.logger = logger; this.locale = Locale.Repository.default; this.loginRoute = Config.routerAuthStepOpts.loginRoute; } run(navigationInstruction, next) { if (!this.session.isUserLoggedIn() && navigationInstruction.config.route !== this.loginRoute)
let canAccess = this.authorize(navigationInstruction); if (canAccess === false) { this.logger.error(this.locale.translate('notAuthorized')); return next.cancel(); } return next(); } authorize(navigationInstruction) { if (navigationInstruction.parentInstruction === null) { return this.canAccess(navigationInstruction); } else { let canAccess = this.canAccess(navigationInstruction); if (hasRole){ return this.authorize(navigationInstruction.parentInstruction) } else { return false; } } } canAccess() { } } @inject(Session, Logger) export class RolesAuthorizeStep extends BaseAuthorizeStep { constructor(session, logger) { super(session, logger); } canAccess(navigationInstruction) { if (navigationInstruction.config.roles) { return this.session.userHasAtLeastOneRole(navigationInstruction.config.roles); } return true; } } @inject(Session, Logger) export class AccessRightsAuthorizeStep extends BaseAuthorizeStep { constructor(session, logger) { super(session, logger); } canAccess(navigationInstruction) { if (navigationInstruction.config.accessRight) { return this.session.userHasAccessRight(navigationInstruction.config.accessRight); } return true; } }
{ this.logger.warn(this.locale.translate('pleaseLogin')); return next.cancel(new Redirect(this.loginRoute)); }
conditional_block
actions.ts
/* * This file is part of CoCalc: Copyright © 2020 Sagemath, Inc. * License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details */ /* Jupyter Frame Editor Actions */ import { delay } from "awaiting"; import { FrameTree } from "../frame-tree/types"; import { Actions, CodeEditorState } from "../code-editor/actions"; import { revealjs_slideshow_html } from "./slideshow-revealjs/nbconvert"; import { create_jupyter_actions, close_jupyter_actions, } from "./jupyter-actions"; interface JupyterEditorState extends CodeEditorState { slideshow?: { state?: "built" | "building" | ""; url?: string; }; } import { JupyterActions } from "../../jupyter/browser-actions"; import { NotebookFrameActions } from "./cell-notebook/actions"; export class JupyterEditorActions extends Actions<JupyterEditorState> { protected doctype: string = "none"; // actual document is managed elsewhere public jupyter_actions: JupyterActions; private frame_actions: { [id: string]: NotebookFrameActions } = {}; _raw_default_frame_tree(): FrameTree { return { type: "jupyter_cell_notebook" }; } _init2(): void { this.create_jupyter_actions(); this.init_new_frame(); this.init_changes_state(); } public close(): void { this.close_jupyter_actions(); super.close(); } private init_new_frame(): void { this.store.on("new-frame", ({ id, type }) => { if (type !== "jupyter_cell_notebook") { return; } // important to do this *before* the frame is rendered, // since it can cause changes during creation. this.get_frame_actions(id); }); for (const id in this._get_leaf_ids()) { const node = this._get_frame_node(id); if (node == null) return; const type = node.get("type"); if (type === "jupyter_cell_notebook") { this.get_frame_actions(id); } } } private init_changes_state(): void { const syncdb = this.jupyter_actions.syncdb; syncdb.on("has-uncommitted-changes", (has_uncommitted_changes) => this.setState({ has_uncommitted_changes }) ); syncdb.on("has-unsaved-changes", (has_unsaved_changes) => { this.setState({ has_unsaved_changes }); }); const store = this.jupyter_actions.store; let introspect = store.get("introspect"); store.on("change", () => { const i = store.get("introspect"); if (i != introspect) { if (i != null) { this.show_introspect(); } else { this.close_introspect(); } introspect = i; } }); } async close_frame_hook(id: string, type: string): Promise<void> { if (type != "jupyter_cell_notebook") return; // TODO: need to free up frame actions when frame is destroyed. if (this.frame_actions[id] != null) { await delay(1); this.frame_actions[id].close(); delete this.frame_actions[id]; } } public focus(id?: string): void { const actions = this.get_frame_actions(id); if (actions != null) { actions.focus(); } else { super.focus(id); } } public refresh(id: string): void { const actions = this.get_frame_actions(id); if (actions != null) { actions.refresh(); } else { super.refresh(id); } } private create_jupyter_actions(): void { this.jupyter_actions = create_jupyter_actions( this.redux, this.name, this.path, this.project_id ); } private close_jupyter_actions(): void { close_jupyter_actions(this.redux, this.name); } public get_frame_actions(id?: string): NotebookFrameActions | undefined { if (id === undefined) { id = this._get_active_id(); if (id == null) throw Error("no active frame"); } if (this.frame_actions[id] != null) { return this.frame_actions[id]; } const node = this._get_frame_node(id); if (node == null) { throw Error(`no frame ${id}`); } const type = node.get("type"); if (type === "jupyter_cell_notebook") { return (this.frame_actions[id] = new NotebookFrameActions(this, id)); } else { return; } } // per-session sync-aware undo undo(id: string): void { id = id; // not used yet, since only one thing that can be undone. this.jupyter_actions.undo(); } // per-session sync-aware redo redo(id: string): void { id = id; // not used yet this.jupyter_actions.redo(); } cut(id: string): void { const actions = this.get_frame_actions(id); actions != null ? actions.cut() : super.cut(id); } copy(id: string): void { const actions = this.get_frame_actions(id); actions != null ? actions.copy() : super.copy(id); } paste(id: string, value?: string | true): void { const actions = this.get_frame_actions(id); actions != null ? actions.paste(value) : super.paste(id, value); } print(_id): void { this.jupyter_actions.show_nbconvert_dialog("html"); } async format(id: string): Promise<void> { const actions = this.get_frame_actions(id); actions != null ? await actions.format() : await super.format(id); } async save(explicit: boolean = true): Promise<void> { explicit = explicit; // not used yet -- might be used for "strip trailing whitespace" // Copy state from live codemirror editor into syncdb // since otherwise it won't be saved to disk. const id = this._active_id(); const a = this.get_frame_actions(id); if (a != null && a.save_input_editor != null) { a.save_input_editor(); } if (!this.jupyter_actions.syncdb.has_unsaved_changes()) return; // Do the save itself, using try/finally to ensure proper // setting of is_saving. try { this.setState({ is_saving: true }); await this.jupyter_actions.save(); } catch (err) { console.warn("save_to_disk", this.path, "ERROR", err); if (this._state == "closed") return; this.set_error(`error saving file to disk -- ${err}`); } finally {
this.setState({ is_saving: false }); } } protected async get_shell_spec( id: string ): Promise<undefined | { command: string; args: string[] }> { id = id; // not used // TODO: need to find out the file that corresponds to // socket and put in args. Can find with ps on the pid. // Also, need to deal with it changing, and shells are // becoming invalid... return { command: "jupyter", args: ["console", "--existing"] }; } // Not an action, but works to make code clean has_format_support(id: string, available_features?): false | string { id = id; const syntax = this.jupyter_actions.store.get_kernel_syntax(); const markdown_only = "Format selected markdown cells using prettier."; if (syntax == null) return markdown_only; if (available_features == null) return markdown_only; const tool = this.format_support_for_syntax(available_features, syntax); if (!tool) return markdown_only; return `Format selected code cells using "${tool}", stopping on first error; formats markdown using prettier.`; } // Uses nbconvert to create an html slideshow version of this notebook. // - If this is foo.ipynb, the resulting slideshow is in the file // .foo.slides.html, so can reference local images, etc. // - Returned string is a **raw url** link to the HTML slideshow file. public async build_revealjs_slideshow(): Promise<void> { const slideshow = (this.store as any).get("slideshow"); if (slideshow != null && slideshow.get("state") == "building") { return; } try { this.setState({ slideshow: { state: "building" } }); this.set_status("Building slideshow: saving...", 10000); await this.save(); if (this._state == "closed") return; this.set_status("Building slideshow: running nbconvert...", 15000); const url = await revealjs_slideshow_html(this.project_id, this.path); if (this._state == "closed") return; this.set_status(""); // really bad design... I need to make this like for courses... this.setState({ slideshow: { state: "built", url } }); } catch (err) { if (this._state == "closed") return; this.set_error(`Error building slideshow -- ${err}`); } } public async build(id: string): Promise<void> { switch (this._get_frame_type(id)) { case "jupyter_slideshow_revealjs": this.build_revealjs_slideshow(); break; } } public show_revealjs_slideshow(): void { this.show_focused_frame_of_type("jupyter_slideshow_revealjs"); this.build_revealjs_slideshow(); } public async jump_to_cell( cell_id: string, align: "center" | "top" = "top" ): Promise<void> { // Open or focus a notebook viewer and scroll to the given cell. if (this._state === "closed") return; const id = this.show_focused_frame_of_type("jupyter_cell_notebook"); const actions = this.get_frame_actions(id); if (actions == null) return; actions.set_cur_id(cell_id); actions.scroll(align == "top" ? "cell top" : "cell visible"); await delay(5); if (this._state === "closed") return; actions.focus(); } public async show_table_of_contents( _id: string | undefined = undefined ): Promise<void> { const id = this.show_focused_frame_of_type( "jupyter_table_of_contents", "col", true, 1 / 3 ); // the click to select TOC focuses the active id back on the notebook await delay(0); if (this._state === "closed") return; this.set_active_id(id, true); } // Either show the most recently focused introspect frame, or ceate one. public async show_introspect(): Promise<void> { this.show_recently_focused_frame_of_type("introspect", "row", false, 2 / 3); } // Close the most recently focused introspect frame, if there is one. public async close_introspect(): Promise<void> { this.close_recently_focused_frame_of_type("introspect"); } }
random_line_split
actions.ts
/* * This file is part of CoCalc: Copyright © 2020 Sagemath, Inc. * License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details */ /* Jupyter Frame Editor Actions */ import { delay } from "awaiting"; import { FrameTree } from "../frame-tree/types"; import { Actions, CodeEditorState } from "../code-editor/actions"; import { revealjs_slideshow_html } from "./slideshow-revealjs/nbconvert"; import { create_jupyter_actions, close_jupyter_actions, } from "./jupyter-actions"; interface JupyterEditorState extends CodeEditorState { slideshow?: { state?: "built" | "building" | ""; url?: string; }; } import { JupyterActions } from "../../jupyter/browser-actions"; import { NotebookFrameActions } from "./cell-notebook/actions"; export class JupyterEditorActions extends Actions<JupyterEditorState> { protected doctype: string = "none"; // actual document is managed elsewhere public jupyter_actions: JupyterActions; private frame_actions: { [id: string]: NotebookFrameActions } = {}; _raw_default_frame_tree(): FrameTree { return { type: "jupyter_cell_notebook" }; } _init2(): void { this.create_jupyter_actions(); this.init_new_frame(); this.init_changes_state(); } public close(): void { this.close_jupyter_actions(); super.close(); } private init_new_frame(): void { this.store.on("new-frame", ({ id, type }) => { if (type !== "jupyter_cell_notebook") { return; } // important to do this *before* the frame is rendered, // since it can cause changes during creation. this.get_frame_actions(id); }); for (const id in this._get_leaf_ids()) { const node = this._get_frame_node(id); if (node == null) return; const type = node.get("type"); if (type === "jupyter_cell_notebook") { this.get_frame_actions(id); } } } private init_changes_state(): void { const syncdb = this.jupyter_actions.syncdb; syncdb.on("has-uncommitted-changes", (has_uncommitted_changes) => this.setState({ has_uncommitted_changes }) ); syncdb.on("has-unsaved-changes", (has_unsaved_changes) => { this.setState({ has_unsaved_changes }); }); const store = this.jupyter_actions.store; let introspect = store.get("introspect"); store.on("change", () => { const i = store.get("introspect"); if (i != introspect) { if (i != null) { this.show_introspect(); } else { this.close_introspect(); } introspect = i; } }); } async close_frame_hook(id: string, type: string): Promise<void> { if (type != "jupyter_cell_notebook") return; // TODO: need to free up frame actions when frame is destroyed. if (this.frame_actions[id] != null) { await delay(1); this.frame_actions[id].close(); delete this.frame_actions[id]; } } public focus(id?: string): void { const actions = this.get_frame_actions(id); if (actions != null) { actions.focus(); } else { super.focus(id); } } public refresh(id: string): void { const actions = this.get_frame_actions(id); if (actions != null) { actions.refresh(); } else { super.refresh(id); } } private create_jupyter_actions(): void { this.jupyter_actions = create_jupyter_actions( this.redux, this.name, this.path, this.project_id ); } private close_jupyter_actions(): void { close_jupyter_actions(this.redux, this.name); } public get_frame_actions(id?: string): NotebookFrameActions | undefined { if (id === undefined) { id = this._get_active_id(); if (id == null) throw Error("no active frame"); } if (this.frame_actions[id] != null) { return this.frame_actions[id]; } const node = this._get_frame_node(id); if (node == null) { throw Error(`no frame ${id}`); } const type = node.get("type"); if (type === "jupyter_cell_notebook") { return (this.frame_actions[id] = new NotebookFrameActions(this, id)); } else { return; } } // per-session sync-aware undo undo(id: string): void { id = id; // not used yet, since only one thing that can be undone. this.jupyter_actions.undo(); } // per-session sync-aware redo redo(id: string): void { id = id; // not used yet this.jupyter_actions.redo(); } cut(id: string): void { const actions = this.get_frame_actions(id); actions != null ? actions.cut() : super.cut(id); } copy(id: string): void { const actions = this.get_frame_actions(id); actions != null ? actions.copy() : super.copy(id); } paste(id: string, value?: string | true): void { const actions = this.get_frame_actions(id); actions != null ? actions.paste(value) : super.paste(id, value); } print(_id): void { this.jupyter_actions.show_nbconvert_dialog("html"); } async format(id: string): Promise<void> { const actions = this.get_frame_actions(id); actions != null ? await actions.format() : await super.format(id); } async save(explicit: boolean = true): Promise<void> { explicit = explicit; // not used yet -- might be used for "strip trailing whitespace" // Copy state from live codemirror editor into syncdb // since otherwise it won't be saved to disk. const id = this._active_id(); const a = this.get_frame_actions(id); if (a != null && a.save_input_editor != null) { a.save_input_editor(); } if (!this.jupyter_actions.syncdb.has_unsaved_changes()) return; // Do the save itself, using try/finally to ensure proper // setting of is_saving. try { this.setState({ is_saving: true }); await this.jupyter_actions.save(); } catch (err) { console.warn("save_to_disk", this.path, "ERROR", err); if (this._state == "closed") return; this.set_error(`error saving file to disk -- ${err}`); } finally { this.setState({ is_saving: false }); } } protected async get_shell_spec( id: string ): Promise<undefined | { command: string; args: string[] }> { id = id; // not used // TODO: need to find out the file that corresponds to // socket and put in args. Can find with ps on the pid. // Also, need to deal with it changing, and shells are // becoming invalid... return { command: "jupyter", args: ["console", "--existing"] }; } // Not an action, but works to make code clean has_format_support(id: string, available_features?): false | string { id = id; const syntax = this.jupyter_actions.store.get_kernel_syntax(); const markdown_only = "Format selected markdown cells using prettier."; if (syntax == null) return markdown_only; if (available_features == null) return markdown_only; const tool = this.format_support_for_syntax(available_features, syntax); if (!tool) return markdown_only; return `Format selected code cells using "${tool}", stopping on first error; formats markdown using prettier.`; } // Uses nbconvert to create an html slideshow version of this notebook. // - If this is foo.ipynb, the resulting slideshow is in the file // .foo.slides.html, so can reference local images, etc. // - Returned string is a **raw url** link to the HTML slideshow file. public async build_revealjs_slideshow(): Promise<void> { const slideshow = (this.store as any).get("slideshow"); if (slideshow != null && slideshow.get("state") == "building") { return; } try { this.setState({ slideshow: { state: "building" } }); this.set_status("Building slideshow: saving...", 10000); await this.save(); if (this._state == "closed") return; this.set_status("Building slideshow: running nbconvert...", 15000); const url = await revealjs_slideshow_html(this.project_id, this.path); if (this._state == "closed") return; this.set_status(""); // really bad design... I need to make this like for courses... this.setState({ slideshow: { state: "built", url } }); } catch (err) { if (this._state == "closed") return; this.set_error(`Error building slideshow -- ${err}`); } } public async build(id: string): Promise<void> { switch (this._get_frame_type(id)) { case "jupyter_slideshow_revealjs": this.build_revealjs_slideshow(); break; } } public show_revealjs_slideshow(): void { this.show_focused_frame_of_type("jupyter_slideshow_revealjs"); this.build_revealjs_slideshow(); } public async jump_to_cell( cell_id: string, align: "center" | "top" = "top" ): Promise<void> { // Open or focus a notebook viewer and scroll to the given cell. if (this._state === "closed") return; const id = this.show_focused_frame_of_type("jupyter_cell_notebook"); const actions = this.get_frame_actions(id); if (actions == null) return; actions.set_cur_id(cell_id); actions.scroll(align == "top" ? "cell top" : "cell visible"); await delay(5); if (this._state === "closed") return; actions.focus(); } public async show_table_of_contents( _id: string | undefined = undefined ): Promise<void> { const id = this.show_focused_frame_of_type( "jupyter_table_of_contents", "col", true, 1 / 3 ); // the click to select TOC focuses the active id back on the notebook await delay(0); if (this._state === "closed") return; this.set_active_id(id, true); } // Either show the most recently focused introspect frame, or ceate one. public async sho
Promise<void> { this.show_recently_focused_frame_of_type("introspect", "row", false, 2 / 3); } // Close the most recently focused introspect frame, if there is one. public async close_introspect(): Promise<void> { this.close_recently_focused_frame_of_type("introspect"); } }
w_introspect():
identifier_name
actions.ts
/* * This file is part of CoCalc: Copyright © 2020 Sagemath, Inc. * License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details */ /* Jupyter Frame Editor Actions */ import { delay } from "awaiting"; import { FrameTree } from "../frame-tree/types"; import { Actions, CodeEditorState } from "../code-editor/actions"; import { revealjs_slideshow_html } from "./slideshow-revealjs/nbconvert"; import { create_jupyter_actions, close_jupyter_actions, } from "./jupyter-actions"; interface JupyterEditorState extends CodeEditorState { slideshow?: { state?: "built" | "building" | ""; url?: string; }; } import { JupyterActions } from "../../jupyter/browser-actions"; import { NotebookFrameActions } from "./cell-notebook/actions"; export class JupyterEditorActions extends Actions<JupyterEditorState> { protected doctype: string = "none"; // actual document is managed elsewhere public jupyter_actions: JupyterActions; private frame_actions: { [id: string]: NotebookFrameActions } = {}; _raw_default_frame_tree(): FrameTree { return { type: "jupyter_cell_notebook" }; } _init2(): void { this.create_jupyter_actions(); this.init_new_frame(); this.init_changes_state(); } public close(): void { this.close_jupyter_actions(); super.close(); } private init_new_frame(): void { this.store.on("new-frame", ({ id, type }) => { if (type !== "jupyter_cell_notebook") { return; } // important to do this *before* the frame is rendered, // since it can cause changes during creation. this.get_frame_actions(id); }); for (const id in this._get_leaf_ids()) { const node = this._get_frame_node(id); if (node == null) return; const type = node.get("type"); if (type === "jupyter_cell_notebook") { this.get_frame_actions(id); } } } private init_changes_state(): void { const syncdb = this.jupyter_actions.syncdb; syncdb.on("has-uncommitted-changes", (has_uncommitted_changes) => this.setState({ has_uncommitted_changes }) ); syncdb.on("has-unsaved-changes", (has_unsaved_changes) => { this.setState({ has_unsaved_changes }); }); const store = this.jupyter_actions.store; let introspect = store.get("introspect"); store.on("change", () => { const i = store.get("introspect"); if (i != introspect) { if (i != null) { this.show_introspect(); } else { this.close_introspect(); } introspect = i; } }); } async close_frame_hook(id: string, type: string): Promise<void> { if (type != "jupyter_cell_notebook") return; // TODO: need to free up frame actions when frame is destroyed. if (this.frame_actions[id] != null) { await delay(1); this.frame_actions[id].close(); delete this.frame_actions[id]; } } public focus(id?: string): void { const actions = this.get_frame_actions(id); if (actions != null) { actions.focus(); } else { super.focus(id); } } public refresh(id: string): void { const actions = this.get_frame_actions(id); if (actions != null) { actions.refresh(); } else { super.refresh(id); } } private create_jupyter_actions(): void { this.jupyter_actions = create_jupyter_actions( this.redux, this.name, this.path, this.project_id ); } private close_jupyter_actions(): void { close_jupyter_actions(this.redux, this.name); } public get_frame_actions(id?: string): NotebookFrameActions | undefined { if (id === undefined) { id = this._get_active_id(); if (id == null) throw Error("no active frame"); } if (this.frame_actions[id] != null) { return this.frame_actions[id]; } const node = this._get_frame_node(id); if (node == null) { throw Error(`no frame ${id}`); } const type = node.get("type"); if (type === "jupyter_cell_notebook") { return (this.frame_actions[id] = new NotebookFrameActions(this, id)); } else { return; } } // per-session sync-aware undo undo(id: string): void { id = id; // not used yet, since only one thing that can be undone. this.jupyter_actions.undo(); } // per-session sync-aware redo redo(id: string): void { id = id; // not used yet this.jupyter_actions.redo(); } cut(id: string): void { const actions = this.get_frame_actions(id); actions != null ? actions.cut() : super.cut(id); } copy(id: string): void { const actions = this.get_frame_actions(id); actions != null ? actions.copy() : super.copy(id); } paste(id: string, value?: string | true): void { const actions = this.get_frame_actions(id); actions != null ? actions.paste(value) : super.paste(id, value); } print(_id): void { this.jupyter_actions.show_nbconvert_dialog("html"); } async format(id: string): Promise<void> { const actions = this.get_frame_actions(id); actions != null ? await actions.format() : await super.format(id); } async save(explicit: boolean = true): Promise<void> { explicit = explicit; // not used yet -- might be used for "strip trailing whitespace" // Copy state from live codemirror editor into syncdb // since otherwise it won't be saved to disk. const id = this._active_id(); const a = this.get_frame_actions(id); if (a != null && a.save_input_editor != null) { a.save_input_editor(); } if (!this.jupyter_actions.syncdb.has_unsaved_changes()) return; // Do the save itself, using try/finally to ensure proper // setting of is_saving. try { this.setState({ is_saving: true }); await this.jupyter_actions.save(); } catch (err) { console.warn("save_to_disk", this.path, "ERROR", err); if (this._state == "closed") return; this.set_error(`error saving file to disk -- ${err}`); } finally { this.setState({ is_saving: false }); } } protected async get_shell_spec( id: string ): Promise<undefined | { command: string; args: string[] }> { id = id; // not used // TODO: need to find out the file that corresponds to // socket and put in args. Can find with ps on the pid. // Also, need to deal with it changing, and shells are // becoming invalid... return { command: "jupyter", args: ["console", "--existing"] }; } // Not an action, but works to make code clean has_format_support(id: string, available_features?): false | string { id = id; const syntax = this.jupyter_actions.store.get_kernel_syntax(); const markdown_only = "Format selected markdown cells using prettier."; if (syntax == null) return markdown_only; if (available_features == null) return markdown_only; const tool = this.format_support_for_syntax(available_features, syntax); if (!tool) return markdown_only; return `Format selected code cells using "${tool}", stopping on first error; formats markdown using prettier.`; } // Uses nbconvert to create an html slideshow version of this notebook. // - If this is foo.ipynb, the resulting slideshow is in the file // .foo.slides.html, so can reference local images, etc. // - Returned string is a **raw url** link to the HTML slideshow file. public async build_revealjs_slideshow(): Promise<void> { const slideshow = (this.store as any).get("slideshow"); if (slideshow != null && slideshow.get("state") == "building") { return; } try { this.setState({ slideshow: { state: "building" } }); this.set_status("Building slideshow: saving...", 10000); await this.save(); if (this._state == "closed") return; this.set_status("Building slideshow: running nbconvert...", 15000); const url = await revealjs_slideshow_html(this.project_id, this.path); if (this._state == "closed") return; this.set_status(""); // really bad design... I need to make this like for courses... this.setState({ slideshow: { state: "built", url } }); } catch (err) { if (this._state == "closed") return; this.set_error(`Error building slideshow -- ${err}`); } } public async build(id: string): Promise<void> { switch (this._get_frame_type(id)) { case "jupyter_slideshow_revealjs": this.build_revealjs_slideshow(); break; } } public show_revealjs_slideshow(): void { this.show_focused_frame_of_type("jupyter_slideshow_revealjs"); this.build_revealjs_slideshow(); } public async jump_to_cell( cell_id: string, align: "center" | "top" = "top" ): Promise<void> { // Open or focus a notebook viewer and scroll to the given cell. if (this._state === "closed") return; const id = this.show_focused_frame_of_type("jupyter_cell_notebook"); const actions = this.get_frame_actions(id); if (actions == null) return; actions.set_cur_id(cell_id); actions.scroll(align == "top" ? "cell top" : "cell visible"); await delay(5); if (this._state === "closed") return; actions.focus(); } public async show_table_of_contents( _id: string | undefined = undefined ): Promise<void> {
// Either show the most recently focused introspect frame, or ceate one. public async show_introspect(): Promise<void> { this.show_recently_focused_frame_of_type("introspect", "row", false, 2 / 3); } // Close the most recently focused introspect frame, if there is one. public async close_introspect(): Promise<void> { this.close_recently_focused_frame_of_type("introspect"); } }
const id = this.show_focused_frame_of_type( "jupyter_table_of_contents", "col", true, 1 / 3 ); // the click to select TOC focuses the active id back on the notebook await delay(0); if (this._state === "closed") return; this.set_active_id(id, true); }
identifier_body
amount-store.ts
import { Map, List, Iterable, Iterator } from 'immutable'; import { Amount, Metric } from './amount'; export interface AmountStore<K, V extends Metric> { store: Map<K, Amount<V>>; } export class AmountStore<K, V extends Metric> implements AmountStore<K, V> { constructor(store: Map<K, Amount<V>>) { this.store = store; } get(key: K):Amount<V> { return this.store.get(key); } set(key: K, value: Amount<V>):Map<K, Amount<V>> { return this.store.set(key, value); } getKeys():Iterator<K> { return this.store.keys(); } update(key: K, newValue: Amount<V>):Map<K, Amount<V>> { return this.store.update(key, value => newValue); } forEach(sideEffect: (value: Amount<V>, key: K, iter: Iterable<K, Amount<V>>) => any):number { return this.store.forEach(sideEffect);
} getStore() { return this.store; } }
random_line_split
amount-store.ts
import { Map, List, Iterable, Iterator } from 'immutable'; import { Amount, Metric } from './amount'; export interface AmountStore<K, V extends Metric> { store: Map<K, Amount<V>>; } export class AmountStore<K, V extends Metric> implements AmountStore<K, V> { constructor(store: Map<K, Amount<V>>) { this.store = store; } get(key: K):Amount<V> { return this.store.get(key); } set(key: K, value: Amount<V>):Map<K, Amount<V>> { return this.store.set(key, value); } getKeys():Iterator<K> { return this.store.keys(); } update(key: K, newValue: Amount<V>):Map<K, Amount<V>> { return this.store.update(key, value => newValue); } forEach(sideEffect: (value: Amount<V>, key: K, iter: Iterable<K, Amount<V>>) => any):number { return this.store.forEach(sideEffect); } getStore()
}
{ return this.store; }
identifier_body
amount-store.ts
import { Map, List, Iterable, Iterator } from 'immutable'; import { Amount, Metric } from './amount'; export interface AmountStore<K, V extends Metric> { store: Map<K, Amount<V>>; } export class AmountStore<K, V extends Metric> implements AmountStore<K, V> { constructor(store: Map<K, Amount<V>>) { this.store = store; } get(key: K):Amount<V> { return this.store.get(key); } set(key: K, value: Amount<V>):Map<K, Amount<V>> { return this.store.set(key, value); } getKeys():Iterator<K> { return this.store.keys(); } update(key: K, newValue: Amount<V>):Map<K, Amount<V>> { return this.store.update(key, value => newValue); } forEach(sideEffect: (value: Amount<V>, key: K, iter: Iterable<K, Amount<V>>) => any):number { return this.store.forEach(sideEffect); }
() { return this.store; } }
getStore
identifier_name
index.tsx
import { Zerotorescue } from 'CONTRIBUTORS'; import NewsRegularArticle from 'interface/NewsRegularArticle'; import React from 'react';
Because Warcraft Logs offers no way to access private logs through the API, your logs must either be unlisted or public if you want to analyze them. If your guild has private logs you will have to <a href="https://www.warcraftlogs.com/help/start/">upload your own logs</a> or change the existing logs to the <i>unlisted</i> privacy option instead. <br /> <br /> Do note that due to a restrictive API request limit we have to aggressively cache all API requests we send to Warcraft Logs. This means that once you run a log through the analyzer, the (secret) link for that log will continue to be accessible even if you change the original log (back) to the private privacy option on Warcraft Logs. Only the fights that you accessed will remain cached indefinitely. <br /> <br /> We will never share links to unlisted or private (analyzed) logs, nor include them recognizably in any public lists. </NewsRegularArticle> );
export const title = 'A note about unlisted logs'; export default ( <NewsRegularArticle title={title} publishedAt="2017-01-31" publishedBy={Zerotorescue}>
random_line_split
os.rs
// Copyright 2014 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. //! Implementation of `std::os` functionality for Windows #![allow(nonstandard_style)] use os::windows::prelude::*; use error::Error as StdError; use ffi::{OsString, OsStr}; use fmt; use io; use os::windows::ffi::EncodeWide; use path::{self, PathBuf}; use ptr; use slice; use sys::{c, cvt}; use sys::handle::Handle; use super::to_u16s; pub fn errno() -> i32 { unsafe { c::GetLastError() as i32 } } /// Gets a detailed string description for the given error number. pub fn error_string(mut errnum: i32) -> String { // This value is calculated from the macro // MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT) let langId = 0x0800 as c::DWORD; let mut buf = [0 as c::WCHAR; 2048]; unsafe { let mut module = ptr::null_mut(); let mut flags = 0; // NTSTATUS errors may be encoded as HRESULT, which may returned from // GetLastError. For more information about Windows error codes, see // `[MS-ERREF]`: https://msdn.microsoft.com/en-us/library/cc231198.aspx if (errnum & c::FACILITY_NT_BIT as i32) != 0 { // format according to https://support.microsoft.com/en-us/help/259693 const NTDLL_DLL: &[u16] = &['N' as _, 'T' as _, 'D' as _, 'L' as _, 'L' as _, '.' as _, 'D' as _, 'L' as _, 'L' as _, 0]; module = c::GetModuleHandleW(NTDLL_DLL.as_ptr()); if module != ptr::null_mut() { errnum ^= c::FACILITY_NT_BIT as i32; flags = c::FORMAT_MESSAGE_FROM_HMODULE; } } let res = c::FormatMessageW(flags | c::FORMAT_MESSAGE_FROM_SYSTEM | c::FORMAT_MESSAGE_IGNORE_INSERTS, module, errnum as c::DWORD, langId, buf.as_mut_ptr(), buf.len() as c::DWORD, ptr::null()) as usize; if res == 0 { // Sometimes FormatMessageW can fail e.g., system doesn't like langId, let fm_err = errno(); return format!("OS Error {} (FormatMessageW() returned error {})", errnum, fm_err); } match String::from_utf16(&buf[..res]) { Ok(mut msg) => { // Trim trailing CRLF inserted by FormatMessageW let len = msg.trim_end().len(); msg.truncate(len); msg }, Err(..) => format!("OS Error {} (FormatMessageW() returned \ invalid UTF-16)", errnum), } } } pub struct Env { base: c::LPWCH, cur: c::LPWCH, } impl Iterator for Env { type Item = (OsString, OsString); fn next(&mut self) -> Option<(OsString, OsString)> { loop { unsafe { if *self.cur == 0 { return None } let p = &*self.cur as *const u16; let mut len = 0; while *p.offset(len) != 0 { len += 1; } let s = slice::from_raw_parts(p, len as usize); self.cur = self.cur.offset(len + 1); // Windows allows environment variables to start with an equals // symbol (in any other position, this is the separator between // variable name and value). Since`s` has at least length 1 at // this point (because the empty string terminates the array of // environment variables), we can safely slice. let pos = match s[1..].iter().position(|&u| u == b'=' as u16).map(|p| p + 1) { Some(p) => p, None => continue, }; return Some(( OsStringExt::from_wide(&s[..pos]), OsStringExt::from_wide(&s[pos+1..]), )) } } } } impl Drop for Env { fn drop(&mut self) { unsafe { c::FreeEnvironmentStringsW(self.base); } } } pub fn env() -> Env { unsafe { let ch = c::GetEnvironmentStringsW(); if ch as usize == 0 { panic!("failure getting env string from OS: {}", io::Error::last_os_error()); } Env { base: ch, cur: ch } } } pub struct SplitPaths<'a> { data: EncodeWide<'a>, must_yield: bool, } pub fn split_paths(unparsed: &OsStr) -> SplitPaths { SplitPaths { data: unparsed.encode_wide(), must_yield: true, } } impl<'a> Iterator for SplitPaths<'a> { type Item = PathBuf; fn next(&mut self) -> Option<PathBuf> { // On Windows, the PATH environment variable is semicolon separated. // Double quotes are used as a way of introducing literal semicolons // (since c:\some;dir is a valid Windows path). Double quotes are not // themselves permitted in path names, so there is no way to escape a // double quote. Quoted regions can appear in arbitrary locations, so // // c:\foo;c:\som"e;di"r;c:\bar // // Should parse as [c:\foo, c:\some;dir, c:\bar]. // // (The above is based on testing; there is no clear reference available // for the grammar.) let must_yield = self.must_yield; self.must_yield = false; let mut in_progress = Vec::new(); let mut in_quote = false; for b in self.data.by_ref() { if b == '"' as u16 { in_quote = !in_quote; } else if b == ';' as u16 && !in_quote { self.must_yield = true; break } else { in_progress.push(b) } } if !must_yield && in_progress.is_empty() { None } else { Some(super::os2path(&in_progress)) } } } #[derive(Debug)] pub struct JoinPathsError; pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError> where I: Iterator<Item=T>, T: AsRef<OsStr> { let mut joined = Vec::new(); let sep = b';' as u16; for (i, path) in paths.enumerate() { let path = path.as_ref(); if i > 0 { joined.push(sep) } let v = path.encode_wide().collect::<Vec<u16>>(); if v.contains(&(b'"' as u16)) { return Err(JoinPathsError) } else if v.contains(&sep) { joined.push(b'"' as u16); joined.extend_from_slice(&v[..]); joined.push(b'"' as u16); } else { joined.extend_from_slice(&v[..]); } } Ok(OsStringExt::from_wide(&joined[..])) } impl fmt::Display for JoinPathsError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { "path segment contains `\"`".fmt(f) } } impl StdError for JoinPathsError { fn description(&self) -> &str { "failed to join paths" } } pub fn current_exe() -> io::Result<PathBuf> { super::fill_utf16_buf(|buf, sz| unsafe { c::GetModuleFileNameW(ptr::null_mut(), buf, sz) }, super::os2path) } pub fn getcwd() -> io::Result<PathBuf> { super::fill_utf16_buf(|buf, sz| unsafe { c::GetCurrentDirectoryW(sz, buf) }, super::os2path) } pub fn chdir(p: &path::Path) -> io::Result<()> { let p: &OsStr = p.as_ref(); let mut p = p.encode_wide().collect::<Vec<_>>(); p.push(0); cvt(unsafe { c::SetCurrentDirectoryW(p.as_ptr()) }).map(|_| ()) } pub fn getenv(k: &OsStr) -> io::Result<Option<OsString>> { let k = to_u16s(k)?; let res = super::fill_utf16_buf(|buf, sz| unsafe { c::GetEnvironmentVariableW(k.as_ptr(), buf, sz) }, |buf| { OsStringExt::from_wide(buf) }); match res { Ok(value) => Ok(Some(value)), Err(e) => { if e.raw_os_error() == Some(c::ERROR_ENVVAR_NOT_FOUND as i32) { Ok(None) } else { Err(e) } } } } pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> { let k = to_u16s(k)?; let v = to_u16s(v)?; cvt(unsafe { c::SetEnvironmentVariableW(k.as_ptr(), v.as_ptr()) }).map(|_| ()) } pub fn unsetenv(n: &OsStr) -> io::Result<()> { let v = to_u16s(n)?; cvt(unsafe { c::SetEnvironmentVariableW(v.as_ptr(), ptr::null()) }).map(|_| ()) } pub fn temp_dir() -> PathBuf { super::fill_utf16_buf(|buf, sz| unsafe { c::GetTempPathW(sz, buf) }, super::os2path).unwrap() } pub fn home_dir() -> Option<PathBuf> { ::env::var_os("HOME").or_else(|| { ::env::var_os("USERPROFILE") }).map(PathBuf::from).or_else(|| unsafe { let me = c::GetCurrentProcess(); let mut token = ptr::null_mut(); if c::OpenProcessToken(me, c::TOKEN_READ, &mut token) == 0 { return None } let _handle = Handle::new(token); super::fill_utf16_buf(|buf, mut sz| { match c::GetUserProfileDirectoryW(token, buf, &mut sz) { 0 if c::GetLastError() != c::ERROR_INSUFFICIENT_BUFFER => 0, 0 => sz, _ => sz - 1, // sz includes the null terminator } }, super::os2path).ok() }) } pub fn exit(code: i32) -> ! { unsafe { c::ExitProcess(code as c::UINT) } } pub fn
() -> u32 { unsafe { c::GetCurrentProcessId() as u32 } } #[cfg(test)] mod tests { use io::Error; use sys::c; // tests `error_string` above #[test] fn ntstatus_error() { const STATUS_UNSUCCESSFUL: u32 = 0xc000_0001; assert!(!Error::from_raw_os_error((STATUS_UNSUCCESSFUL | c::FACILITY_NT_BIT) as _) .to_string().contains("FormatMessageW() returned error")); } }
getpid
identifier_name
os.rs
// Copyright 2014 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. //! Implementation of `std::os` functionality for Windows #![allow(nonstandard_style)] use os::windows::prelude::*; use error::Error as StdError; use ffi::{OsString, OsStr}; use fmt; use io; use os::windows::ffi::EncodeWide; use path::{self, PathBuf}; use ptr; use slice; use sys::{c, cvt}; use sys::handle::Handle; use super::to_u16s; pub fn errno() -> i32 { unsafe { c::GetLastError() as i32 } } /// Gets a detailed string description for the given error number. pub fn error_string(mut errnum: i32) -> String { // This value is calculated from the macro // MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT) let langId = 0x0800 as c::DWORD; let mut buf = [0 as c::WCHAR; 2048]; unsafe { let mut module = ptr::null_mut(); let mut flags = 0; // NTSTATUS errors may be encoded as HRESULT, which may returned from // GetLastError. For more information about Windows error codes, see // `[MS-ERREF]`: https://msdn.microsoft.com/en-us/library/cc231198.aspx if (errnum & c::FACILITY_NT_BIT as i32) != 0 { // format according to https://support.microsoft.com/en-us/help/259693 const NTDLL_DLL: &[u16] = &['N' as _, 'T' as _, 'D' as _, 'L' as _, 'L' as _, '.' as _, 'D' as _, 'L' as _, 'L' as _, 0]; module = c::GetModuleHandleW(NTDLL_DLL.as_ptr()); if module != ptr::null_mut() { errnum ^= c::FACILITY_NT_BIT as i32; flags = c::FORMAT_MESSAGE_FROM_HMODULE; } } let res = c::FormatMessageW(flags | c::FORMAT_MESSAGE_FROM_SYSTEM | c::FORMAT_MESSAGE_IGNORE_INSERTS, module, errnum as c::DWORD, langId, buf.as_mut_ptr(), buf.len() as c::DWORD, ptr::null()) as usize; if res == 0 { // Sometimes FormatMessageW can fail e.g., system doesn't like langId, let fm_err = errno(); return format!("OS Error {} (FormatMessageW() returned error {})", errnum, fm_err); } match String::from_utf16(&buf[..res]) { Ok(mut msg) => { // Trim trailing CRLF inserted by FormatMessageW let len = msg.trim_end().len(); msg.truncate(len); msg }, Err(..) => format!("OS Error {} (FormatMessageW() returned \ invalid UTF-16)", errnum), } } } pub struct Env { base: c::LPWCH, cur: c::LPWCH, } impl Iterator for Env { type Item = (OsString, OsString); fn next(&mut self) -> Option<(OsString, OsString)> { loop { unsafe { if *self.cur == 0 { return None } let p = &*self.cur as *const u16; let mut len = 0; while *p.offset(len) != 0 { len += 1; } let s = slice::from_raw_parts(p, len as usize); self.cur = self.cur.offset(len + 1); // Windows allows environment variables to start with an equals // symbol (in any other position, this is the separator between // variable name and value). Since`s` has at least length 1 at // this point (because the empty string terminates the array of // environment variables), we can safely slice. let pos = match s[1..].iter().position(|&u| u == b'=' as u16).map(|p| p + 1) { Some(p) => p, None => continue, }; return Some(( OsStringExt::from_wide(&s[..pos]), OsStringExt::from_wide(&s[pos+1..]), )) } } } } impl Drop for Env { fn drop(&mut self) { unsafe { c::FreeEnvironmentStringsW(self.base); } } } pub fn env() -> Env { unsafe { let ch = c::GetEnvironmentStringsW(); if ch as usize == 0 { panic!("failure getting env string from OS: {}", io::Error::last_os_error()); } Env { base: ch, cur: ch } } } pub struct SplitPaths<'a> { data: EncodeWide<'a>, must_yield: bool, } pub fn split_paths(unparsed: &OsStr) -> SplitPaths { SplitPaths { data: unparsed.encode_wide(), must_yield: true, } } impl<'a> Iterator for SplitPaths<'a> { type Item = PathBuf; fn next(&mut self) -> Option<PathBuf> { // On Windows, the PATH environment variable is semicolon separated. // Double quotes are used as a way of introducing literal semicolons // (since c:\some;dir is a valid Windows path). Double quotes are not // themselves permitted in path names, so there is no way to escape a // double quote. Quoted regions can appear in arbitrary locations, so // // c:\foo;c:\som"e;di"r;c:\bar // // Should parse as [c:\foo, c:\some;dir, c:\bar]. // // (The above is based on testing; there is no clear reference available // for the grammar.) let must_yield = self.must_yield; self.must_yield = false; let mut in_progress = Vec::new(); let mut in_quote = false; for b in self.data.by_ref() { if b == '"' as u16 { in_quote = !in_quote; } else if b == ';' as u16 && !in_quote { self.must_yield = true; break } else { in_progress.push(b) } } if !must_yield && in_progress.is_empty() { None } else { Some(super::os2path(&in_progress)) } } } #[derive(Debug)] pub struct JoinPathsError; pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError> where I: Iterator<Item=T>, T: AsRef<OsStr> { let mut joined = Vec::new(); let sep = b';' as u16; for (i, path) in paths.enumerate() { let path = path.as_ref(); if i > 0 { joined.push(sep) } let v = path.encode_wide().collect::<Vec<u16>>(); if v.contains(&(b'"' as u16)) { return Err(JoinPathsError) } else if v.contains(&sep)
else { joined.extend_from_slice(&v[..]); } } Ok(OsStringExt::from_wide(&joined[..])) } impl fmt::Display for JoinPathsError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { "path segment contains `\"`".fmt(f) } } impl StdError for JoinPathsError { fn description(&self) -> &str { "failed to join paths" } } pub fn current_exe() -> io::Result<PathBuf> { super::fill_utf16_buf(|buf, sz| unsafe { c::GetModuleFileNameW(ptr::null_mut(), buf, sz) }, super::os2path) } pub fn getcwd() -> io::Result<PathBuf> { super::fill_utf16_buf(|buf, sz| unsafe { c::GetCurrentDirectoryW(sz, buf) }, super::os2path) } pub fn chdir(p: &path::Path) -> io::Result<()> { let p: &OsStr = p.as_ref(); let mut p = p.encode_wide().collect::<Vec<_>>(); p.push(0); cvt(unsafe { c::SetCurrentDirectoryW(p.as_ptr()) }).map(|_| ()) } pub fn getenv(k: &OsStr) -> io::Result<Option<OsString>> { let k = to_u16s(k)?; let res = super::fill_utf16_buf(|buf, sz| unsafe { c::GetEnvironmentVariableW(k.as_ptr(), buf, sz) }, |buf| { OsStringExt::from_wide(buf) }); match res { Ok(value) => Ok(Some(value)), Err(e) => { if e.raw_os_error() == Some(c::ERROR_ENVVAR_NOT_FOUND as i32) { Ok(None) } else { Err(e) } } } } pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> { let k = to_u16s(k)?; let v = to_u16s(v)?; cvt(unsafe { c::SetEnvironmentVariableW(k.as_ptr(), v.as_ptr()) }).map(|_| ()) } pub fn unsetenv(n: &OsStr) -> io::Result<()> { let v = to_u16s(n)?; cvt(unsafe { c::SetEnvironmentVariableW(v.as_ptr(), ptr::null()) }).map(|_| ()) } pub fn temp_dir() -> PathBuf { super::fill_utf16_buf(|buf, sz| unsafe { c::GetTempPathW(sz, buf) }, super::os2path).unwrap() } pub fn home_dir() -> Option<PathBuf> { ::env::var_os("HOME").or_else(|| { ::env::var_os("USERPROFILE") }).map(PathBuf::from).or_else(|| unsafe { let me = c::GetCurrentProcess(); let mut token = ptr::null_mut(); if c::OpenProcessToken(me, c::TOKEN_READ, &mut token) == 0 { return None } let _handle = Handle::new(token); super::fill_utf16_buf(|buf, mut sz| { match c::GetUserProfileDirectoryW(token, buf, &mut sz) { 0 if c::GetLastError() != c::ERROR_INSUFFICIENT_BUFFER => 0, 0 => sz, _ => sz - 1, // sz includes the null terminator } }, super::os2path).ok() }) } pub fn exit(code: i32) -> ! { unsafe { c::ExitProcess(code as c::UINT) } } pub fn getpid() -> u32 { unsafe { c::GetCurrentProcessId() as u32 } } #[cfg(test)] mod tests { use io::Error; use sys::c; // tests `error_string` above #[test] fn ntstatus_error() { const STATUS_UNSUCCESSFUL: u32 = 0xc000_0001; assert!(!Error::from_raw_os_error((STATUS_UNSUCCESSFUL | c::FACILITY_NT_BIT) as _) .to_string().contains("FormatMessageW() returned error")); } }
{ joined.push(b'"' as u16); joined.extend_from_slice(&v[..]); joined.push(b'"' as u16); }
conditional_block
os.rs
// Copyright 2014 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. //! Implementation of `std::os` functionality for Windows #![allow(nonstandard_style)] use os::windows::prelude::*; use error::Error as StdError; use ffi::{OsString, OsStr}; use fmt; use io; use os::windows::ffi::EncodeWide; use path::{self, PathBuf}; use ptr; use slice; use sys::{c, cvt}; use sys::handle::Handle; use super::to_u16s; pub fn errno() -> i32 { unsafe { c::GetLastError() as i32 } } /// Gets a detailed string description for the given error number. pub fn error_string(mut errnum: i32) -> String { // This value is calculated from the macro // MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT) let langId = 0x0800 as c::DWORD; let mut buf = [0 as c::WCHAR; 2048]; unsafe { let mut module = ptr::null_mut(); let mut flags = 0; // NTSTATUS errors may be encoded as HRESULT, which may returned from // GetLastError. For more information about Windows error codes, see // `[MS-ERREF]`: https://msdn.microsoft.com/en-us/library/cc231198.aspx if (errnum & c::FACILITY_NT_BIT as i32) != 0 { // format according to https://support.microsoft.com/en-us/help/259693 const NTDLL_DLL: &[u16] = &['N' as _, 'T' as _, 'D' as _, 'L' as _, 'L' as _, '.' as _, 'D' as _, 'L' as _, 'L' as _, 0]; module = c::GetModuleHandleW(NTDLL_DLL.as_ptr()); if module != ptr::null_mut() { errnum ^= c::FACILITY_NT_BIT as i32; flags = c::FORMAT_MESSAGE_FROM_HMODULE; } } let res = c::FormatMessageW(flags | c::FORMAT_MESSAGE_FROM_SYSTEM | c::FORMAT_MESSAGE_IGNORE_INSERTS, module, errnum as c::DWORD, langId, buf.as_mut_ptr(), buf.len() as c::DWORD, ptr::null()) as usize; if res == 0 { // Sometimes FormatMessageW can fail e.g., system doesn't like langId, let fm_err = errno(); return format!("OS Error {} (FormatMessageW() returned error {})", errnum, fm_err); } match String::from_utf16(&buf[..res]) { Ok(mut msg) => { // Trim trailing CRLF inserted by FormatMessageW let len = msg.trim_end().len(); msg.truncate(len); msg }, Err(..) => format!("OS Error {} (FormatMessageW() returned \ invalid UTF-16)", errnum), } } } pub struct Env { base: c::LPWCH, cur: c::LPWCH, } impl Iterator for Env { type Item = (OsString, OsString); fn next(&mut self) -> Option<(OsString, OsString)>
} impl Drop for Env { fn drop(&mut self) { unsafe { c::FreeEnvironmentStringsW(self.base); } } } pub fn env() -> Env { unsafe { let ch = c::GetEnvironmentStringsW(); if ch as usize == 0 { panic!("failure getting env string from OS: {}", io::Error::last_os_error()); } Env { base: ch, cur: ch } } } pub struct SplitPaths<'a> { data: EncodeWide<'a>, must_yield: bool, } pub fn split_paths(unparsed: &OsStr) -> SplitPaths { SplitPaths { data: unparsed.encode_wide(), must_yield: true, } } impl<'a> Iterator for SplitPaths<'a> { type Item = PathBuf; fn next(&mut self) -> Option<PathBuf> { // On Windows, the PATH environment variable is semicolon separated. // Double quotes are used as a way of introducing literal semicolons // (since c:\some;dir is a valid Windows path). Double quotes are not // themselves permitted in path names, so there is no way to escape a // double quote. Quoted regions can appear in arbitrary locations, so // // c:\foo;c:\som"e;di"r;c:\bar // // Should parse as [c:\foo, c:\some;dir, c:\bar]. // // (The above is based on testing; there is no clear reference available // for the grammar.) let must_yield = self.must_yield; self.must_yield = false; let mut in_progress = Vec::new(); let mut in_quote = false; for b in self.data.by_ref() { if b == '"' as u16 { in_quote = !in_quote; } else if b == ';' as u16 && !in_quote { self.must_yield = true; break } else { in_progress.push(b) } } if !must_yield && in_progress.is_empty() { None } else { Some(super::os2path(&in_progress)) } } } #[derive(Debug)] pub struct JoinPathsError; pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError> where I: Iterator<Item=T>, T: AsRef<OsStr> { let mut joined = Vec::new(); let sep = b';' as u16; for (i, path) in paths.enumerate() { let path = path.as_ref(); if i > 0 { joined.push(sep) } let v = path.encode_wide().collect::<Vec<u16>>(); if v.contains(&(b'"' as u16)) { return Err(JoinPathsError) } else if v.contains(&sep) { joined.push(b'"' as u16); joined.extend_from_slice(&v[..]); joined.push(b'"' as u16); } else { joined.extend_from_slice(&v[..]); } } Ok(OsStringExt::from_wide(&joined[..])) } impl fmt::Display for JoinPathsError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { "path segment contains `\"`".fmt(f) } } impl StdError for JoinPathsError { fn description(&self) -> &str { "failed to join paths" } } pub fn current_exe() -> io::Result<PathBuf> { super::fill_utf16_buf(|buf, sz| unsafe { c::GetModuleFileNameW(ptr::null_mut(), buf, sz) }, super::os2path) } pub fn getcwd() -> io::Result<PathBuf> { super::fill_utf16_buf(|buf, sz| unsafe { c::GetCurrentDirectoryW(sz, buf) }, super::os2path) } pub fn chdir(p: &path::Path) -> io::Result<()> { let p: &OsStr = p.as_ref(); let mut p = p.encode_wide().collect::<Vec<_>>(); p.push(0); cvt(unsafe { c::SetCurrentDirectoryW(p.as_ptr()) }).map(|_| ()) } pub fn getenv(k: &OsStr) -> io::Result<Option<OsString>> { let k = to_u16s(k)?; let res = super::fill_utf16_buf(|buf, sz| unsafe { c::GetEnvironmentVariableW(k.as_ptr(), buf, sz) }, |buf| { OsStringExt::from_wide(buf) }); match res { Ok(value) => Ok(Some(value)), Err(e) => { if e.raw_os_error() == Some(c::ERROR_ENVVAR_NOT_FOUND as i32) { Ok(None) } else { Err(e) } } } } pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> { let k = to_u16s(k)?; let v = to_u16s(v)?; cvt(unsafe { c::SetEnvironmentVariableW(k.as_ptr(), v.as_ptr()) }).map(|_| ()) } pub fn unsetenv(n: &OsStr) -> io::Result<()> { let v = to_u16s(n)?; cvt(unsafe { c::SetEnvironmentVariableW(v.as_ptr(), ptr::null()) }).map(|_| ()) } pub fn temp_dir() -> PathBuf { super::fill_utf16_buf(|buf, sz| unsafe { c::GetTempPathW(sz, buf) }, super::os2path).unwrap() } pub fn home_dir() -> Option<PathBuf> { ::env::var_os("HOME").or_else(|| { ::env::var_os("USERPROFILE") }).map(PathBuf::from).or_else(|| unsafe { let me = c::GetCurrentProcess(); let mut token = ptr::null_mut(); if c::OpenProcessToken(me, c::TOKEN_READ, &mut token) == 0 { return None } let _handle = Handle::new(token); super::fill_utf16_buf(|buf, mut sz| { match c::GetUserProfileDirectoryW(token, buf, &mut sz) { 0 if c::GetLastError() != c::ERROR_INSUFFICIENT_BUFFER => 0, 0 => sz, _ => sz - 1, // sz includes the null terminator } }, super::os2path).ok() }) } pub fn exit(code: i32) -> ! { unsafe { c::ExitProcess(code as c::UINT) } } pub fn getpid() -> u32 { unsafe { c::GetCurrentProcessId() as u32 } } #[cfg(test)] mod tests { use io::Error; use sys::c; // tests `error_string` above #[test] fn ntstatus_error() { const STATUS_UNSUCCESSFUL: u32 = 0xc000_0001; assert!(!Error::from_raw_os_error((STATUS_UNSUCCESSFUL | c::FACILITY_NT_BIT) as _) .to_string().contains("FormatMessageW() returned error")); } }
{ loop { unsafe { if *self.cur == 0 { return None } let p = &*self.cur as *const u16; let mut len = 0; while *p.offset(len) != 0 { len += 1; } let s = slice::from_raw_parts(p, len as usize); self.cur = self.cur.offset(len + 1); // Windows allows environment variables to start with an equals // symbol (in any other position, this is the separator between // variable name and value). Since`s` has at least length 1 at // this point (because the empty string terminates the array of // environment variables), we can safely slice. let pos = match s[1..].iter().position(|&u| u == b'=' as u16).map(|p| p + 1) { Some(p) => p, None => continue, }; return Some(( OsStringExt::from_wide(&s[..pos]), OsStringExt::from_wide(&s[pos+1..]), )) } } }
identifier_body
os.rs
// Copyright 2014 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. //! Implementation of `std::os` functionality for Windows #![allow(nonstandard_style)] use os::windows::prelude::*; use error::Error as StdError; use ffi::{OsString, OsStr}; use fmt; use io; use os::windows::ffi::EncodeWide; use path::{self, PathBuf}; use ptr; use slice; use sys::{c, cvt}; use sys::handle::Handle; use super::to_u16s; pub fn errno() -> i32 { unsafe { c::GetLastError() as i32 } } /// Gets a detailed string description for the given error number. pub fn error_string(mut errnum: i32) -> String { // This value is calculated from the macro // MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT) let langId = 0x0800 as c::DWORD; let mut buf = [0 as c::WCHAR; 2048]; unsafe { let mut module = ptr::null_mut(); let mut flags = 0; // NTSTATUS errors may be encoded as HRESULT, which may returned from // GetLastError. For more information about Windows error codes, see // `[MS-ERREF]`: https://msdn.microsoft.com/en-us/library/cc231198.aspx if (errnum & c::FACILITY_NT_BIT as i32) != 0 { // format according to https://support.microsoft.com/en-us/help/259693 const NTDLL_DLL: &[u16] = &['N' as _, 'T' as _, 'D' as _, 'L' as _, 'L' as _, '.' as _, 'D' as _, 'L' as _, 'L' as _, 0]; module = c::GetModuleHandleW(NTDLL_DLL.as_ptr()); if module != ptr::null_mut() { errnum ^= c::FACILITY_NT_BIT as i32; flags = c::FORMAT_MESSAGE_FROM_HMODULE; } } let res = c::FormatMessageW(flags | c::FORMAT_MESSAGE_FROM_SYSTEM | c::FORMAT_MESSAGE_IGNORE_INSERTS, module, errnum as c::DWORD, langId, buf.as_mut_ptr(), buf.len() as c::DWORD, ptr::null()) as usize; if res == 0 { // Sometimes FormatMessageW can fail e.g., system doesn't like langId, let fm_err = errno(); return format!("OS Error {} (FormatMessageW() returned error {})", errnum, fm_err); } match String::from_utf16(&buf[..res]) { Ok(mut msg) => { // Trim trailing CRLF inserted by FormatMessageW let len = msg.trim_end().len(); msg.truncate(len); msg }, Err(..) => format!("OS Error {} (FormatMessageW() returned \ invalid UTF-16)", errnum), } } } pub struct Env { base: c::LPWCH, cur: c::LPWCH, } impl Iterator for Env { type Item = (OsString, OsString); fn next(&mut self) -> Option<(OsString, OsString)> { loop { unsafe { if *self.cur == 0 { return None } let p = &*self.cur as *const u16; let mut len = 0; while *p.offset(len) != 0 { len += 1; } let s = slice::from_raw_parts(p, len as usize); self.cur = self.cur.offset(len + 1); // Windows allows environment variables to start with an equals // symbol (in any other position, this is the separator between // variable name and value). Since`s` has at least length 1 at // this point (because the empty string terminates the array of // environment variables), we can safely slice. let pos = match s[1..].iter().position(|&u| u == b'=' as u16).map(|p| p + 1) { Some(p) => p, None => continue, }; return Some(( OsStringExt::from_wide(&s[..pos]), OsStringExt::from_wide(&s[pos+1..]), )) } } } } impl Drop for Env { fn drop(&mut self) { unsafe { c::FreeEnvironmentStringsW(self.base); } } } pub fn env() -> Env { unsafe { let ch = c::GetEnvironmentStringsW(); if ch as usize == 0 { panic!("failure getting env string from OS: {}", io::Error::last_os_error()); } Env { base: ch, cur: ch } } } pub struct SplitPaths<'a> { data: EncodeWide<'a>, must_yield: bool, } pub fn split_paths(unparsed: &OsStr) -> SplitPaths { SplitPaths { data: unparsed.encode_wide(), must_yield: true, } } impl<'a> Iterator for SplitPaths<'a> { type Item = PathBuf; fn next(&mut self) -> Option<PathBuf> { // On Windows, the PATH environment variable is semicolon separated. // Double quotes are used as a way of introducing literal semicolons // (since c:\some;dir is a valid Windows path). Double quotes are not // themselves permitted in path names, so there is no way to escape a // double quote. Quoted regions can appear in arbitrary locations, so // // c:\foo;c:\som"e;di"r;c:\bar // // Should parse as [c:\foo, c:\some;dir, c:\bar]. // // (The above is based on testing; there is no clear reference available // for the grammar.) let must_yield = self.must_yield; self.must_yield = false; let mut in_progress = Vec::new(); let mut in_quote = false; for b in self.data.by_ref() { if b == '"' as u16 { in_quote = !in_quote; } else if b == ';' as u16 && !in_quote { self.must_yield = true; break
if !must_yield && in_progress.is_empty() { None } else { Some(super::os2path(&in_progress)) } } } #[derive(Debug)] pub struct JoinPathsError; pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError> where I: Iterator<Item=T>, T: AsRef<OsStr> { let mut joined = Vec::new(); let sep = b';' as u16; for (i, path) in paths.enumerate() { let path = path.as_ref(); if i > 0 { joined.push(sep) } let v = path.encode_wide().collect::<Vec<u16>>(); if v.contains(&(b'"' as u16)) { return Err(JoinPathsError) } else if v.contains(&sep) { joined.push(b'"' as u16); joined.extend_from_slice(&v[..]); joined.push(b'"' as u16); } else { joined.extend_from_slice(&v[..]); } } Ok(OsStringExt::from_wide(&joined[..])) } impl fmt::Display for JoinPathsError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { "path segment contains `\"`".fmt(f) } } impl StdError for JoinPathsError { fn description(&self) -> &str { "failed to join paths" } } pub fn current_exe() -> io::Result<PathBuf> { super::fill_utf16_buf(|buf, sz| unsafe { c::GetModuleFileNameW(ptr::null_mut(), buf, sz) }, super::os2path) } pub fn getcwd() -> io::Result<PathBuf> { super::fill_utf16_buf(|buf, sz| unsafe { c::GetCurrentDirectoryW(sz, buf) }, super::os2path) } pub fn chdir(p: &path::Path) -> io::Result<()> { let p: &OsStr = p.as_ref(); let mut p = p.encode_wide().collect::<Vec<_>>(); p.push(0); cvt(unsafe { c::SetCurrentDirectoryW(p.as_ptr()) }).map(|_| ()) } pub fn getenv(k: &OsStr) -> io::Result<Option<OsString>> { let k = to_u16s(k)?; let res = super::fill_utf16_buf(|buf, sz| unsafe { c::GetEnvironmentVariableW(k.as_ptr(), buf, sz) }, |buf| { OsStringExt::from_wide(buf) }); match res { Ok(value) => Ok(Some(value)), Err(e) => { if e.raw_os_error() == Some(c::ERROR_ENVVAR_NOT_FOUND as i32) { Ok(None) } else { Err(e) } } } } pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> { let k = to_u16s(k)?; let v = to_u16s(v)?; cvt(unsafe { c::SetEnvironmentVariableW(k.as_ptr(), v.as_ptr()) }).map(|_| ()) } pub fn unsetenv(n: &OsStr) -> io::Result<()> { let v = to_u16s(n)?; cvt(unsafe { c::SetEnvironmentVariableW(v.as_ptr(), ptr::null()) }).map(|_| ()) } pub fn temp_dir() -> PathBuf { super::fill_utf16_buf(|buf, sz| unsafe { c::GetTempPathW(sz, buf) }, super::os2path).unwrap() } pub fn home_dir() -> Option<PathBuf> { ::env::var_os("HOME").or_else(|| { ::env::var_os("USERPROFILE") }).map(PathBuf::from).or_else(|| unsafe { let me = c::GetCurrentProcess(); let mut token = ptr::null_mut(); if c::OpenProcessToken(me, c::TOKEN_READ, &mut token) == 0 { return None } let _handle = Handle::new(token); super::fill_utf16_buf(|buf, mut sz| { match c::GetUserProfileDirectoryW(token, buf, &mut sz) { 0 if c::GetLastError() != c::ERROR_INSUFFICIENT_BUFFER => 0, 0 => sz, _ => sz - 1, // sz includes the null terminator } }, super::os2path).ok() }) } pub fn exit(code: i32) -> ! { unsafe { c::ExitProcess(code as c::UINT) } } pub fn getpid() -> u32 { unsafe { c::GetCurrentProcessId() as u32 } } #[cfg(test)] mod tests { use io::Error; use sys::c; // tests `error_string` above #[test] fn ntstatus_error() { const STATUS_UNSUCCESSFUL: u32 = 0xc000_0001; assert!(!Error::from_raw_os_error((STATUS_UNSUCCESSFUL | c::FACILITY_NT_BIT) as _) .to_string().contains("FormatMessageW() returned error")); } }
} else { in_progress.push(b) } }
random_line_split
base_props.rs
use crate::core::{Directedness, Graph}; use num_traits::{One, PrimInt, Unsigned, Zero}; use std::borrow::Borrow; /// A graph where new vertices can be added pub trait NewVertex: Graph { /// Adds a new vertex with the given weight to the graph. /// Returns the id of the new vertex. fn new_vertex_weighted(&mut self, w: Self::VertexWeight) -> Result<Self::Vertex, ()>; // Optional methods /// Adds a new vertex to the graph. /// Returns the id of the new vertex. /// The weight of the vertex is the default. fn new_vertex(&mut self) -> Result<Self::Vertex, ()> where Self::VertexWeight: Default, { self.new_vertex_weighted(Self::VertexWeight::default()) } } /// A graph where vertices can be removed. /// /// Removing a vertex may invalidate existing vertices. pub trait RemoveVertex: Graph { /// Removes the given vertex from the graph, returning its weight. /// If the vertex still has edges incident on it, they are also removed, /// dropping their weights. fn remove_vertex(&mut self, v: impl Borrow<Self::Vertex>) -> Result<Self::VertexWeight, ()>; } pub trait AddEdge: Graph { /// Adds a copy of the given edge to the graph fn add_edge_weighted( &mut self, source: impl Borrow<Self::Vertex>, sink: impl Borrow<Self::Vertex>, weight: Self::EdgeWeight, ) -> Result<(), ()>; // Optional methods /// Adds the given edge to the graph, regardless of whether there are /// existing, identical edges in the graph. /// The vertices the new edge is incident on must exist in the graph and the /// id must be valid. /// /// ###Returns /// - `Ok` if the edge is valid and was added to the graph. /// - `Err` if the edge is invalid or the graph was otherwise unable to /// store it. /// /// ###`Ok` properties: /// /// - Only the given edge is added to the graph. /// - Existing edges are unchanged. /// - No vertices are introduced or removed. /// /// ###`Err` properties: /// /// - The graph is unchanged. fn add_edge( &mut self, source: impl Borrow<Self::Vertex>, sink: impl Borrow<Self::Vertex>, ) -> Result<(), ()> where Self::EdgeWeight: Default, { self.add_edge_weighted(source, sink, Self::EdgeWeight::default()) } } pub trait RemoveEdge: Graph { fn remove_edge_where_weight<F>( &mut self, source: impl Borrow<Self::Vertex>, sink: impl Borrow<Self::Vertex>, f: F, ) -> Result<Self::EdgeWeight, ()> where F: Fn(&Self::EdgeWeight) -> bool; // Optional methods /// Removes an edge source in v1 and sinked in v2. /// /// ###Returns /// - `Ok` if the edge was present before the call and was removed. /// - `Err` if the edge was not found in the graph or it was otherwise /// unable to remove it. /// /// ###`Ok` properties: /// /// - One edge identical to the given edge is removed. /// - No new edges are introduced. /// - No edges are changed. /// - No new vertices are introduced or removed. /// /// ###`Err` properties: /// /// - The graph is unchanged. fn remove_edge( &mut self, source: impl Borrow<Self::Vertex>, sink: impl Borrow<Self::Vertex>, ) -> Result<Self::EdgeWeight, ()> { self.remove_edge_where_weight(source, sink, |_| true) } } /// A graph with a finite number of vertices that can be counted. pub trait VertexCount: Graph { type Count: PrimInt + Unsigned; /// Returns the number of vertices in the graph. fn vertex_count(&self) -> Self::Count { let mut count = Self::Count::zero(); let mut verts = self.all_vertices(); while let Some(_) = verts.next() { count = count + Self::Count::one(); } count } } /// A graph with a finite number of edges that can be counted. pub trait EdgeCount: Graph { type Count: PrimInt + Unsigned; /// Returns the number of vertices in the graph. fn edge_count(&self) -> Self::Count { let mut count = Self::Count::zero(); let mut inc = || count = count + Self::Count::one(); let verts: Vec<_> = self.all_vertices().collect(); let mut iter = verts.iter(); let mut rest_iter = iter.clone(); while let Some(v) = iter.next() { for v2 in rest_iter { self.edges_between(v.borrow(), v2.borrow()) .for_each(|_| inc()); if Self::Directedness::directed()
} rest_iter = iter.clone(); } count } }
{ self.edges_between(v2.borrow(), v.borrow()) .for_each(|_| inc()); }
conditional_block
base_props.rs
use crate::core::{Directedness, Graph}; use num_traits::{One, PrimInt, Unsigned, Zero}; use std::borrow::Borrow; /// A graph where new vertices can be added pub trait NewVertex: Graph { /// Adds a new vertex with the given weight to the graph. /// Returns the id of the new vertex. fn new_vertex_weighted(&mut self, w: Self::VertexWeight) -> Result<Self::Vertex, ()>; // Optional methods /// Adds a new vertex to the graph. /// Returns the id of the new vertex. /// The weight of the vertex is the default. fn new_vertex(&mut self) -> Result<Self::Vertex, ()> where Self::VertexWeight: Default, { self.new_vertex_weighted(Self::VertexWeight::default()) } } /// A graph where vertices can be removed. /// /// Removing a vertex may invalidate existing vertices. pub trait RemoveVertex: Graph { /// Removes the given vertex from the graph, returning its weight. /// If the vertex still has edges incident on it, they are also removed, /// dropping their weights. fn remove_vertex(&mut self, v: impl Borrow<Self::Vertex>) -> Result<Self::VertexWeight, ()>; } pub trait AddEdge: Graph { /// Adds a copy of the given edge to the graph fn add_edge_weighted( &mut self, source: impl Borrow<Self::Vertex>, sink: impl Borrow<Self::Vertex>, weight: Self::EdgeWeight, ) -> Result<(), ()>; // Optional methods /// Adds the given edge to the graph, regardless of whether there are /// existing, identical edges in the graph. /// The vertices the new edge is incident on must exist in the graph and the /// id must be valid. /// /// ###Returns /// - `Ok` if the edge is valid and was added to the graph. /// - `Err` if the edge is invalid or the graph was otherwise unable to /// store it. /// /// ###`Ok` properties: ///
/// - No vertices are introduced or removed. /// /// ###`Err` properties: /// /// - The graph is unchanged. fn add_edge( &mut self, source: impl Borrow<Self::Vertex>, sink: impl Borrow<Self::Vertex>, ) -> Result<(), ()> where Self::EdgeWeight: Default, { self.add_edge_weighted(source, sink, Self::EdgeWeight::default()) } } pub trait RemoveEdge: Graph { fn remove_edge_where_weight<F>( &mut self, source: impl Borrow<Self::Vertex>, sink: impl Borrow<Self::Vertex>, f: F, ) -> Result<Self::EdgeWeight, ()> where F: Fn(&Self::EdgeWeight) -> bool; // Optional methods /// Removes an edge source in v1 and sinked in v2. /// /// ###Returns /// - `Ok` if the edge was present before the call and was removed. /// - `Err` if the edge was not found in the graph or it was otherwise /// unable to remove it. /// /// ###`Ok` properties: /// /// - One edge identical to the given edge is removed. /// - No new edges are introduced. /// - No edges are changed. /// - No new vertices are introduced or removed. /// /// ###`Err` properties: /// /// - The graph is unchanged. fn remove_edge( &mut self, source: impl Borrow<Self::Vertex>, sink: impl Borrow<Self::Vertex>, ) -> Result<Self::EdgeWeight, ()> { self.remove_edge_where_weight(source, sink, |_| true) } } /// A graph with a finite number of vertices that can be counted. pub trait VertexCount: Graph { type Count: PrimInt + Unsigned; /// Returns the number of vertices in the graph. fn vertex_count(&self) -> Self::Count { let mut count = Self::Count::zero(); let mut verts = self.all_vertices(); while let Some(_) = verts.next() { count = count + Self::Count::one(); } count } } /// A graph with a finite number of edges that can be counted. pub trait EdgeCount: Graph { type Count: PrimInt + Unsigned; /// Returns the number of vertices in the graph. fn edge_count(&self) -> Self::Count { let mut count = Self::Count::zero(); let mut inc = || count = count + Self::Count::one(); let verts: Vec<_> = self.all_vertices().collect(); let mut iter = verts.iter(); let mut rest_iter = iter.clone(); while let Some(v) = iter.next() { for v2 in rest_iter { self.edges_between(v.borrow(), v2.borrow()) .for_each(|_| inc()); if Self::Directedness::directed() { self.edges_between(v2.borrow(), v.borrow()) .for_each(|_| inc()); } } rest_iter = iter.clone(); } count } }
/// - Only the given edge is added to the graph. /// - Existing edges are unchanged.
random_line_split
base_props.rs
use crate::core::{Directedness, Graph}; use num_traits::{One, PrimInt, Unsigned, Zero}; use std::borrow::Borrow; /// A graph where new vertices can be added pub trait NewVertex: Graph { /// Adds a new vertex with the given weight to the graph. /// Returns the id of the new vertex. fn new_vertex_weighted(&mut self, w: Self::VertexWeight) -> Result<Self::Vertex, ()>; // Optional methods /// Adds a new vertex to the graph. /// Returns the id of the new vertex. /// The weight of the vertex is the default. fn new_vertex(&mut self) -> Result<Self::Vertex, ()> where Self::VertexWeight: Default,
} /// A graph where vertices can be removed. /// /// Removing a vertex may invalidate existing vertices. pub trait RemoveVertex: Graph { /// Removes the given vertex from the graph, returning its weight. /// If the vertex still has edges incident on it, they are also removed, /// dropping their weights. fn remove_vertex(&mut self, v: impl Borrow<Self::Vertex>) -> Result<Self::VertexWeight, ()>; } pub trait AddEdge: Graph { /// Adds a copy of the given edge to the graph fn add_edge_weighted( &mut self, source: impl Borrow<Self::Vertex>, sink: impl Borrow<Self::Vertex>, weight: Self::EdgeWeight, ) -> Result<(), ()>; // Optional methods /// Adds the given edge to the graph, regardless of whether there are /// existing, identical edges in the graph. /// The vertices the new edge is incident on must exist in the graph and the /// id must be valid. /// /// ###Returns /// - `Ok` if the edge is valid and was added to the graph. /// - `Err` if the edge is invalid or the graph was otherwise unable to /// store it. /// /// ###`Ok` properties: /// /// - Only the given edge is added to the graph. /// - Existing edges are unchanged. /// - No vertices are introduced or removed. /// /// ###`Err` properties: /// /// - The graph is unchanged. fn add_edge( &mut self, source: impl Borrow<Self::Vertex>, sink: impl Borrow<Self::Vertex>, ) -> Result<(), ()> where Self::EdgeWeight: Default, { self.add_edge_weighted(source, sink, Self::EdgeWeight::default()) } } pub trait RemoveEdge: Graph { fn remove_edge_where_weight<F>( &mut self, source: impl Borrow<Self::Vertex>, sink: impl Borrow<Self::Vertex>, f: F, ) -> Result<Self::EdgeWeight, ()> where F: Fn(&Self::EdgeWeight) -> bool; // Optional methods /// Removes an edge source in v1 and sinked in v2. /// /// ###Returns /// - `Ok` if the edge was present before the call and was removed. /// - `Err` if the edge was not found in the graph or it was otherwise /// unable to remove it. /// /// ###`Ok` properties: /// /// - One edge identical to the given edge is removed. /// - No new edges are introduced. /// - No edges are changed. /// - No new vertices are introduced or removed. /// /// ###`Err` properties: /// /// - The graph is unchanged. fn remove_edge( &mut self, source: impl Borrow<Self::Vertex>, sink: impl Borrow<Self::Vertex>, ) -> Result<Self::EdgeWeight, ()> { self.remove_edge_where_weight(source, sink, |_| true) } } /// A graph with a finite number of vertices that can be counted. pub trait VertexCount: Graph { type Count: PrimInt + Unsigned; /// Returns the number of vertices in the graph. fn vertex_count(&self) -> Self::Count { let mut count = Self::Count::zero(); let mut verts = self.all_vertices(); while let Some(_) = verts.next() { count = count + Self::Count::one(); } count } } /// A graph with a finite number of edges that can be counted. pub trait EdgeCount: Graph { type Count: PrimInt + Unsigned; /// Returns the number of vertices in the graph. fn edge_count(&self) -> Self::Count { let mut count = Self::Count::zero(); let mut inc = || count = count + Self::Count::one(); let verts: Vec<_> = self.all_vertices().collect(); let mut iter = verts.iter(); let mut rest_iter = iter.clone(); while let Some(v) = iter.next() { for v2 in rest_iter { self.edges_between(v.borrow(), v2.borrow()) .for_each(|_| inc()); if Self::Directedness::directed() { self.edges_between(v2.borrow(), v.borrow()) .for_each(|_| inc()); } } rest_iter = iter.clone(); } count } }
{ self.new_vertex_weighted(Self::VertexWeight::default()) }
identifier_body
base_props.rs
use crate::core::{Directedness, Graph}; use num_traits::{One, PrimInt, Unsigned, Zero}; use std::borrow::Borrow; /// A graph where new vertices can be added pub trait NewVertex: Graph { /// Adds a new vertex with the given weight to the graph. /// Returns the id of the new vertex. fn new_vertex_weighted(&mut self, w: Self::VertexWeight) -> Result<Self::Vertex, ()>; // Optional methods /// Adds a new vertex to the graph. /// Returns the id of the new vertex. /// The weight of the vertex is the default. fn new_vertex(&mut self) -> Result<Self::Vertex, ()> where Self::VertexWeight: Default, { self.new_vertex_weighted(Self::VertexWeight::default()) } } /// A graph where vertices can be removed. /// /// Removing a vertex may invalidate existing vertices. pub trait RemoveVertex: Graph { /// Removes the given vertex from the graph, returning its weight. /// If the vertex still has edges incident on it, they are also removed, /// dropping their weights. fn remove_vertex(&mut self, v: impl Borrow<Self::Vertex>) -> Result<Self::VertexWeight, ()>; } pub trait AddEdge: Graph { /// Adds a copy of the given edge to the graph fn add_edge_weighted( &mut self, source: impl Borrow<Self::Vertex>, sink: impl Borrow<Self::Vertex>, weight: Self::EdgeWeight, ) -> Result<(), ()>; // Optional methods /// Adds the given edge to the graph, regardless of whether there are /// existing, identical edges in the graph. /// The vertices the new edge is incident on must exist in the graph and the /// id must be valid. /// /// ###Returns /// - `Ok` if the edge is valid and was added to the graph. /// - `Err` if the edge is invalid or the graph was otherwise unable to /// store it. /// /// ###`Ok` properties: /// /// - Only the given edge is added to the graph. /// - Existing edges are unchanged. /// - No vertices are introduced or removed. /// /// ###`Err` properties: /// /// - The graph is unchanged. fn
( &mut self, source: impl Borrow<Self::Vertex>, sink: impl Borrow<Self::Vertex>, ) -> Result<(), ()> where Self::EdgeWeight: Default, { self.add_edge_weighted(source, sink, Self::EdgeWeight::default()) } } pub trait RemoveEdge: Graph { fn remove_edge_where_weight<F>( &mut self, source: impl Borrow<Self::Vertex>, sink: impl Borrow<Self::Vertex>, f: F, ) -> Result<Self::EdgeWeight, ()> where F: Fn(&Self::EdgeWeight) -> bool; // Optional methods /// Removes an edge source in v1 and sinked in v2. /// /// ###Returns /// - `Ok` if the edge was present before the call and was removed. /// - `Err` if the edge was not found in the graph or it was otherwise /// unable to remove it. /// /// ###`Ok` properties: /// /// - One edge identical to the given edge is removed. /// - No new edges are introduced. /// - No edges are changed. /// - No new vertices are introduced or removed. /// /// ###`Err` properties: /// /// - The graph is unchanged. fn remove_edge( &mut self, source: impl Borrow<Self::Vertex>, sink: impl Borrow<Self::Vertex>, ) -> Result<Self::EdgeWeight, ()> { self.remove_edge_where_weight(source, sink, |_| true) } } /// A graph with a finite number of vertices that can be counted. pub trait VertexCount: Graph { type Count: PrimInt + Unsigned; /// Returns the number of vertices in the graph. fn vertex_count(&self) -> Self::Count { let mut count = Self::Count::zero(); let mut verts = self.all_vertices(); while let Some(_) = verts.next() { count = count + Self::Count::one(); } count } } /// A graph with a finite number of edges that can be counted. pub trait EdgeCount: Graph { type Count: PrimInt + Unsigned; /// Returns the number of vertices in the graph. fn edge_count(&self) -> Self::Count { let mut count = Self::Count::zero(); let mut inc = || count = count + Self::Count::one(); let verts: Vec<_> = self.all_vertices().collect(); let mut iter = verts.iter(); let mut rest_iter = iter.clone(); while let Some(v) = iter.next() { for v2 in rest_iter { self.edges_between(v.borrow(), v2.borrow()) .for_each(|_| inc()); if Self::Directedness::directed() { self.edges_between(v2.borrow(), v.borrow()) .for_each(|_| inc()); } } rest_iter = iter.clone(); } count } }
add_edge
identifier_name
sw.js
/** * Copyright 2018 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
workbox.precaching.precacheAndRoute([]); workbox.routing.registerRoute(/\.(?:html|css)$/, workbox.strategies.cacheFirst({ cacheName: 'pages', }) ); workbox.routing.registerRoute(/\.(?:png|gif|jpg)$/, workbox.strategies.cacheFirst({ cacheName: 'images', plugins: [ new workbox.expiration.Plugin({ maxEntries: 50 }) ] }) );
importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.4.1/workbox-sw.js');
random_line_split
signal-exit-status.rs
// Copyright 2014 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. // copyright 2013-2014 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. // ignore-win32 use std::os; use std::io::process::{Process, ExitSignal, ExitStatus}; pub fn main()
{ let args = os::args(); let args = args.as_slice(); if args.len() >= 2 && args[1] == "signal".to_owned() { // Raise a segfault. unsafe { *(0 as *mut int) = 0; } } else { let status = Process::status(args[0], ["signal".to_owned()]).unwrap(); // Windows does not have signal, so we get exit status 0xC0000028 (STATUS_BAD_STACK). match status { ExitSignal(_) if cfg!(unix) => {}, ExitStatus(0xC0000028) if cfg!(windows) => {}, _ => fail!("invalid termination (was not signalled): {:?}", status) } } }
identifier_body
signal-exit-status.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// 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. // copyright 2013-2014 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. // ignore-win32 use std::os; use std::io::process::{Process, ExitSignal, ExitStatus}; pub fn main() { let args = os::args(); let args = args.as_slice(); if args.len() >= 2 && args[1] == "signal".to_owned() { // Raise a segfault. unsafe { *(0 as *mut int) = 0; } } else { let status = Process::status(args[0], ["signal".to_owned()]).unwrap(); // Windows does not have signal, so we get exit status 0xC0000028 (STATUS_BAD_STACK). match status { ExitSignal(_) if cfg!(unix) => {}, ExitStatus(0xC0000028) if cfg!(windows) => {}, _ => fail!("invalid termination (was not signalled): {:?}", status) } } }
// 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
random_line_split
signal-exit-status.rs
// Copyright 2014 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. // copyright 2013-2014 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. // ignore-win32 use std::os; use std::io::process::{Process, ExitSignal, ExitStatus}; pub fn main() { let args = os::args(); let args = args.as_slice(); if args.len() >= 2 && args[1] == "signal".to_owned() { // Raise a segfault. unsafe { *(0 as *mut int) = 0; } } else
}
{ let status = Process::status(args[0], ["signal".to_owned()]).unwrap(); // Windows does not have signal, so we get exit status 0xC0000028 (STATUS_BAD_STACK). match status { ExitSignal(_) if cfg!(unix) => {}, ExitStatus(0xC0000028) if cfg!(windows) => {}, _ => fail!("invalid termination (was not signalled): {:?}", status) } }
conditional_block
signal-exit-status.rs
// Copyright 2014 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. // copyright 2013-2014 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. // ignore-win32 use std::os; use std::io::process::{Process, ExitSignal, ExitStatus}; pub fn
() { let args = os::args(); let args = args.as_slice(); if args.len() >= 2 && args[1] == "signal".to_owned() { // Raise a segfault. unsafe { *(0 as *mut int) = 0; } } else { let status = Process::status(args[0], ["signal".to_owned()]).unwrap(); // Windows does not have signal, so we get exit status 0xC0000028 (STATUS_BAD_STACK). match status { ExitSignal(_) if cfg!(unix) => {}, ExitStatus(0xC0000028) if cfg!(windows) => {}, _ => fail!("invalid termination (was not signalled): {:?}", status) } } }
main
identifier_name
setup_plugin.py
''' Pixie: FreeBSD virtualization guest configuration client Copyright (C) 2011 The Hotel Communication Network inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import threading, Queue as queue, time, subprocess, shlex, datetime import urllib, tarfile, os, shutil, tempfile, pwd import cherrypy from cherrypy.process import wspbus, plugins from pixie.lib.jails import EzJail from pixie.lib.interfaces import NetInterfaces class SetupTask(object): def __init__(self, puck, queue): self.queue = queue self._puck = puck self.vm = puck.getVM() def run(self): raise NotImplementedError("`run` must be defined.") def log(self, msg): now = datetime.datetime.now() cherrypy.log("%s %s" % (self.__class__.__name__, msg)) tpl = "%s\t%s\t%s" date_format = "%Y-%m-%d %H:%M:%S" cls = self.__class__.__name__ self.queue.put(tpl % (now.strftime(date_format), cls, msg)) class RcReader(object): def _has_line(self, lines, line_start): for line in lines: if line.startswith(line_start): return True return False def _get_rc_content(self): rc = None try: with open('/etc/rc.conf', 'r') as f: rc = f.readlines() except IOError: pass if not rc: raise RuntimeError("File `/etc/rc.conf` is empty!") return rc class EZJailTask(SetupTask, RcReader): ''' Setups ezjail in the virtual machine. ''' def run(self): try: self.log("Enabling EZJail.") self._enable_ezjail() self.log("Installing EZJail") EzJail().install(cherrypy.config.get('setup_plugin.ftp_mirror')) except (IOError, OSError) as e: self.log("Error while installing ezjail: %s" % e) return False return True def _enable_ezjail(self): rc = self._get_rc_content() if self._has_line(rc, 'ezjail_enable'): self.log("EZJail is already enabled.") return self.log("Adding to rc: `%s`" % 'ezjail_enable="YES"') '''if we get here, it means ezjail_enable is not in rc.conf''' with open('/etc/rc.conf', 'a') as f: f.write("ezjail_enable=\"YES\"\n") class SSHTask(SetupTask): '''Create the base user `puck` and add the authorized ssh keys''' def run(self): self._setup_ssh() return True def _setup_ssh(self): if not self.vm.keys: self.log("No keys to install."); return True #@TODO Could be moved to config values instead of hardcoded. user = 'puck' try: pwd.getpwnam(user) except KeyError as e: cmd = 'pw user add %s -m -G wheel' % user self.log("Adding user. Executing `%s`" % cmd) subprocess.Popen(shlex.split(str(cmd))).wait() user_pwd = pwd.getpwnam(user) path = '/home/%s/.ssh' % user authorized_file = "%s/authorized_keys" % path if not os.path.exists(path): os.mkdir(path) os.chown(path, user_pwd.pw_uid, user_pwd.pw_gid) with open(authorized_file, 'a') as f: for key in self.vm.keys: self.log("Writing key `%s`" % key) f.write('%s\n' % self.vm.keys[key]['key']) os.chmod(authorized_file, 0400) os.chown(authorized_file, user_pwd.pw_uid, user_pwd.pw_gid) os.chmod(path, 0700) os.chmod('/home/%s' % user, 0700) class FirewallSetupTask(SetupTask, RcReader): def run(self): # TODO Move this to a congfiguration value from puck. Not high priority pf_conf = '/etc/pf.rules.conf' rc_conf = '/etc/rc.conf' self.setup_rc(rc_conf, pf_conf) self.setup_pf_conf(pf_conf) self.launch_pf() return True def launch_pf(self): # Stop it in case it commands = ['/etc/rc.d/pf stop', '/etc/rc.d/pf start'] for command in commands: self.log("Executing: `%s`" % command) subprocess.Popen(shlex.split(str(command))).wait() def setup_pf_conf(self, pf_conf): rules = self.vm.firewall if not rules: self.log("No firewall to write.") return False self.log("Writing firewall rules at `%s`." % pf_conf) with open(pf_conf, 'w') as f: f.write(rules.replace('\r\n', '\n').replace('\r', '\n')) f.flush() def setup_rc(self, rc_conf, pf_conf): #TODO Move this to a configuration value. Not high priority. rc_items = { 'pf_enable' : 'YES', 'pf_rules' : pf_conf, 'pflog_enable' : 'YES', 'gateway_enable' : 'YES' } rc_present = [] rc = self._get_rc_content() for line in rc: for k in rc_items: if line.startswith(k): rc_present.append(k) break missing = set(rc_items.keys()) - set(rc_present) tpl = 'Adding to rc: `%s="%s"`' [self.log(tpl % (k, rc_items[k])) for k in missing] template = '%s="%s"\n' with open(rc_conf, 'a') as f: [f.write(template % (k,rc_items[k])) for k in missing] f.flush() class InterfacesSetupTask(SetupTask, RcReader): '''Configures network interfaces for the jails.''' def run(self): (netaddrs, missing) = self._get_missing_netaddrs() self._add_missing_netaddrs(missing) self._add_missing_rc(netaddrs) return True def _add_missing_rc(self, netaddrs): rc_addresses = [] rc = self._get_rc_content() alias_count = self._calculate_alias_count(rc_addresses, rc) with open('/etc/rc.conf', 'a') as f: for netaddr in netaddrs: if self._add_rc_ip(rc_addresses, f, alias_count, netaddr): alias_count += 1 def _add_missing_netaddrs(self, netaddrs): for netaddr in netaddrs: self.log("Registering new ip address `%s`" % netaddr['ip']) self._add_addr(netaddr['ip'], netaddr['netmask']) def _get_missing_netaddrs(self): interfaces = NetInterfaces.getInterfaces() missing = [] netaddrs = [] for jail in self.vm.jails: netaddr = {'ip': jail.ip, 'netmask': jail.netmask} netaddrs.append(netaddr) if not interfaces.has_key(jail.ip): missing.append(netaddr) return (netaddrs, missing) def _calculate_alias_count(self, addresses, rc): alias_count = 0 for line in rc: if line.startswith('ifconfig_%s_alias' % self.vm.interface): alias_count += 1 addresses.append(line) return alias_count def _add_addr(self, ip, netmask): cmd = "ifconfig %s alias %s netmask %s" command = cmd % (self.vm.interface, ip, netmask) self.log('executing: `%s`' % command) subprocess.Popen(shlex.split(str(command))).wait() def _add_rc_ip(self, rc_addresses, file, alias_count, netaddr): for item in rc_addresses: if item.find(netaddr['ip']) > 0: self.log("rc already knows about ip `%s`" % netaddr['ip']) return False self.log("Registering new rc value for ip `%s`" % netaddr['ip']) template = 'ifconfig_%s_alias%s="inet %s netmask %s"' line = "%s\n" % template values = ( self.vm.interface, alias_count, netaddr['ip'], netaddr['netmask'] ) file.write(line % values) file.flush() return True class HypervisorSetupTask(SetupTask, RcReader): ''' Setups a few hypervisor settings such as Shared Memory/IPC ''' def run(self): self._add_rc_settings() self._add_sysctl_settings() self._set_hostname() return True def _set_hostname(self): self.log("Replacing hostname in /etc/rc.conf") (fh, abspath) = tempfile.mkstemp() tmp = open(abspath, 'w') with open('/etc/rc.conf', 'r') as f: for line in f: if not line.startswith('hostname'): tmp.write(line) continue tmp.write('hostname="%s"\n' % self.vm.name) tmp.close() os.close(fh) os.remove('/etc/rc.conf') shutil.move(abspath, '/etc/rc.conf') os.chmod('/etc/rc.conf', 0644) cmd = str('hostname %s' % self.vm.name) self.log('Executing: `%s`' % cmd) subprocess.Popen(shlex.split(cmd)).wait() def _add_sysctl_settings(self): sysvipc = cherrypy.config.get('hypervisor.jail_sysvipc_allow') ipc_setting = 'security.jail.sysvipc_allowed' self.log("Configuring sysctl") with open('/etc/sysctl.conf', 'r') as f: sysctl = f.readlines() if sysvipc: cmd = str("sysctl %s=1" % ipc_setting) self.log('Executing: `%s`' % cmd) subprocess.Popen(shlex.split(cmd)).wait() if self._has_line(sysctl, ipc_setting): self.log('SysV IPC already configured in sysctl.conf') return template = '%s=%s\n' data = template % (ipc_setting, 1) self.log('Adding to sysctl.conf: `%s`' % data) with open('/etc/sysctl.conf', 'a') as f: f.write(data) def _add_rc_settings(self): items = [ 'jail_sysvipc_allow', 'syslogd_flags' ] rc = self._get_rc_content() # settings will contain items to be added to rc settings = {} for i in items: value = cherrypy.config.get('hypervisor.%s' % i) if not value: continue if self._has_line(rc, i): continue self.log('Adding to rc: `%s="%s"`' % (i, value)) settings[i] = value # settings now contains items to be added template = '%s="%s"\n' with open('/etc/rc.conf', 'a') as f: [f.write(template % (k, settings[k])) for k in settings] f.flush() class EZJailSetupTask(SetupTask): ''' Setups ezjail in the virtual machine ''' def run(self): base_dir = cherrypy.config.get('setup_plugin.jail_dir') dst_dir = '%s/flavours' % base_dir if not os.path.isdir(dst_dir): try: self.log("Creating folder `%s`." % dst_dir) os.makedirs(dst_dir) except OSError as e: self.log('Could not create folder `%s`' % dst_dir) return False # Holds the temporary file list tmpfiles = self._retrieveFlavours() if not tmpfiles: self.log('No flavours downloaded.') return False # Verify and extract the flavour tarball for file in tmpfiles: # Verify if not tarfile.is_tarfile(file['tmp_file']): msg = "File `%s` is not a tarfile." self.log(msg % file['tmp_file']) return False self.log('Extracting `%s`' % file['tmp_file']) # Extraction try: with tarfile.open(file['tmp_file'], mode='r:*') as t: '''Will raise KeyError if file does not exists.''' if not t.getmember(file['type']).isdir(): msg ="Tar member `%s` is not a folder." raise tarfile.ExtractError(msg % file['type']) t.extractall("%s/" % dst_dir) except (IOError, KeyError, tarfile.ExtractError) as e: msg = "File `%s` could not be extracted. Reason: %s" self.log(msg % (file['tmp_file'], e)) # Remove the temporary tarball try: os.unlink(file['tmp_file']) except OSerror as e: msg = "Error while removing file `%s`: %s" self.log(msg % (file['tmp_file'], e)) return True def _retrieveFlavours(self): '''Retrieve the tarball for each flavours''' tmpfiles = [] jail_dir = cherrypy.config.get('setup_plugin.jail_dir') for jail in self.vm.jails: (handle, tmpname) = tempfile.mkstemp(dir=jail_dir) self.log("Fetching flavour `%s` at `%s`" % (jail.name, jail.url)) try: (filename, headers) = urllib.urlretrieve(jail.url, tmpname) except (urllib.ContentTooShortError, IOError) as e: msg = "Error while retrieving jail `%s`: %s" self.log(msg % (jail.name, e)) return False tmpfiles.append({'type': jail.jail_type, 'tmp_file': filename}) self.log("Jail `%s` downloaded at `%s`" % (jail.name, filename)) return tmpfiles class JailConfigTask(SetupTask): ''' Handles jails configuration ''' def run(self): jail_dir = cherrypy.config.get('setup_plugin.jail_dir') flavour_dir = "%s/flavours" % jail_dir for jail in self.vm.jails: self.log("Configuring jail `%s`." % jail.jail_type) path = "%s/%s" % (flavour_dir, jail.jail_type) authorized_key_file = "%s/installdata/authorized_keys" % path resolv_file = "%s/etc/resolv.conf" % path yum_file = "%s/installdata/yum_repo" % path rc_file = "%s/etc/rc.conf" % path host_file = "%s/etc/hosts" % path # Create /installdata and /etc folder. for p in ['%s/installdata', '%s/etc']: if not os.path.exists(p % path): os.mkdir(p % path) # Verify the flavours exists. exists = os.path.exists(path) is_dir = os.path.isdir(path) if not exists or not is_dir: msg = "Flavour `%s` directory is missing in `%s." self.log(msg % (jail.jail_type, flavour_dir)) return False msg = "Retrieving yum repository for environment `%s`." self.log(msg % self.vm.environment) yum_repo = self._puck.getYumRepo(self.vm.environment) self.log("Writing ssh keys.") if not self._writeKeys(jail, authorized_key_file): return False self.log("Copying resolv.conf.") if not self._writeResolvConf(jail, resolv_file): return False self.log("Updating jail hostname to `%s-%s`" % (self.vm.name, jail.jail_type)) if not self._update_hostname(jail, rc_file, host_file): return False self.log("Writing yum repository.") if not self._writeYumRepoConf(yum_repo, yum_file): return False self.log("Creating jail.") if not self._createJail(jail): return False return True def _writeKeys(self, jail, authorized_key_file): '''Write authorized keys''' try: with open(authorized_key_file, 'w') as f: for key in self.vm.keys.values(): f.write("%s\n" % key['key']) except IOError as e: msg = "Error while writing authorized keys to jail `%s`: %s" self.log(msg % (jail.jail_type, e)) return False return True def _update_hostname(self, jail, rc_file, host_file): hostname = "%s-%s" % (self.vm.name, jail.jail_type) self.log("Replacing hostname in %s" % rc_file) (fh, abspath) = tempfile.mkstemp() has_hostname = False tmp = open(abspath, 'w') with open(rc_file, 'r') as f: for line in f: if not line.startswith('hostname'): tmp.write(line) continue tmp.write('hostname="%s"\n' % hostname) has_hostname = True if not has_hostname: tmp.write('hostname="%s"\n' % hostname) tmp.close() os.close(fh) os.remove(rc_file) shutil.move(abspath, rc_file) os.chmod(rc_file, 0644) self.log("Adding new hostname in %s" % host_file) (fh, abspath) = tempfile.mkstemp() has_hostname = False tmp = open(abspath, 'w') with open(host_file, 'r') as f: for line in f: if not line.startswith('127.0.0.1'): tmp.write(line) continue tmp.write('%s %s\n' % (line.replace('\n', ''), hostname)) tmp.close() os.close(fh) os.remove(host_file) shutil.move(abspath, host_file) os.chmod(host_file, 0644) return True def _writeResolvConf(self, jail, resolv_file): '''Copy resolv.conf''' try: shutil.copyfile('/etc/resolv.conf', resolv_file) except IOError as e: self.log("Error while copying host resolv file: %s" % e) return False return True def _writeYumRepoConf(self, yum_repo, yum_file): '''Setup yum repo.d file ezjail will use.''' try: with open(yum_file, 'w') as f: f.write(yum_repo['data']) except (KeyError, IOError) as e: self.log("Error while writing YUM repo data: %s" % e) return False return True def
(self, jail): '''Create the jail''' try: jail.create() except OSError as e: msg = "Error while installing jail `%s`: %s" self.log(msg % (jail.jail_type, e)) return False return True class JailStartupTask(SetupTask): ''' Handles starting each jail. ''' def run(self): # Start each jail for jail in self.vm.jails: self.log("Starting jail `%s`" % jail.jail_type) try: status = jail.start() except OSError as e: self.log("Could not start jail `%s`: %s" % (jail.jail_type, e)) return False self.log("Jail status: %s" % status) self.log("Jail `%s` started" % jail.jail_type) if not jail.status(): self.log("Jail `%s` is not running!" % jail.jail_type) return False return True class SetupWorkerThread(threading.Thread): """ Thread class with a stop() method. The thread itself has to check regularly for the stopped() condition. """ def __init__(self, bus, queue, outqueue, puck): super(self.__class__, self).__init__() self._stop = threading.Event() self.running = threading.Event() self.successful = False self.completed = False self._queue = queue self._bus = bus self._outqueue = outqueue self._puck = puck def stop(self): self._stop.set() def stopped(self): return self._stop.isSet() def _step(self): ''' Run a task @raise RuntimeError when the task failed to complete ''' # This will probably need to be wrapped in a try/catch. task = self._queue.get(True, 10)(self._puck, self._outqueue) loginfo = (self.__class__.__name__, task.__class__.__name__) task.log('Starting') if not task.run(): raise RuntimeError("%s error while running task `%s`" % loginfo) task.log('Completed') self._queue.task_done() def run(self): if self.completed: self._bus.log("%s had already been run." % self.__class__.__name__) return False if self.running.isSet(): self._bus.log("%s is already running." % self.__class__.__name__) return False self.running.set() self._bus.log("%s started." % self.__class__.__name__) try: while not self.stopped(): self._step() except RuntimeError as err: self._bus.log(str(err)) self._empty_queue() self._puck.getVM().status = 'setup_failed' self._puck.updateStatus() self.succesful = False self.completed = True return False except queue.Empty: pass self.completed = True self.sucessful = True self._puck.getVM().status = 'setup_complete' self._puck.updateStatus() self._outqueue.put("%s finished." % self.__class__.__name__) def _empty_queue(self): while not self._queue.empty(): try: self._queue.get(False) except queue.Empty: return class SetupPlugin(plugins.SimplePlugin): ''' Handles tasks related to virtual machine setup. The plugin launches a separate thread to asynchronously execute the tasks. ''' def __init__(self, puck, bus, freq=30.0): plugins.SimplePlugin.__init__(self, bus) self.freq = freq self._puck = puck self._queue = queue.Queue() self._workerQueue = queue.Queue() self.worker = None self.statuses = [] def start(self): self.bus.log('Starting up setup tasks') self.bus.subscribe('setup', self.switch) start.priority = 70 def stop(self): self.bus.log('Stopping down setup task.') self._setup_stop(); def switch(self, *args, **kwargs): ''' This is the task switchboard. Depending on the parameters received, it will execute the appropriate action. ''' if not 'action' in kwargs: self.log("Parameter `action` is missing.") return # Default task def default(**kwargs): return return { 'start': self._setup_start, 'stop': self._setup_stop, 'status': self._setup_status, 'clear': self._clear_status }.get(kwargs['action'], default)() def _clear_status(self, **kwargs): '''Clear the status list''' del(self.statuses[:]) def _setup_stop(self, **kwargs): self.bus.log("Received stop request.") if self.worker and self.worker.isAlive(): self.worker.stop() def _start_worker(self): self.worker = SetupWorkerThread( bus=self.bus, queue = self._queue, outqueue = self._workerQueue, puck = self._puck ) self.worker.start() def _setup_start(self, **kwargs): self.bus.log("Received start request.") # Start the worker if it is not running. if not self.worker: self._start_worker() if not self.worker.is_alive() and not self.worker.successful: self._start_worker() # @TODO: Persistence of the list when failure occurs. # or a state machine instead of a queue. for task in cherrypy.config.get('setup_plugin.tasks'): self._queue.put(task) def _setup_status(self, **kwargs): ''' Returns the current log queue and if the setup is running or not. ''' status = self._readQueue(self._workerQueue) while status: self.statuses.append(status) status = self._readQueue(self._workerQueue) if not self.worker or not self.worker.isAlive(): return (self.statuses, False) return (self.statuses, True) def _readQueue(self, q, blocking = True, timeout = 0.2): ''' Wraps code to read from a queue, including exception handling. ''' try: item = q.get(blocking, timeout) except queue.Empty: return None return item
_createJail
identifier_name
setup_plugin.py
''' Pixie: FreeBSD virtualization guest configuration client Copyright (C) 2011 The Hotel Communication Network inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import threading, Queue as queue, time, subprocess, shlex, datetime import urllib, tarfile, os, shutil, tempfile, pwd import cherrypy from cherrypy.process import wspbus, plugins from pixie.lib.jails import EzJail from pixie.lib.interfaces import NetInterfaces class SetupTask(object): def __init__(self, puck, queue): self.queue = queue self._puck = puck self.vm = puck.getVM() def run(self): raise NotImplementedError("`run` must be defined.") def log(self, msg): now = datetime.datetime.now() cherrypy.log("%s %s" % (self.__class__.__name__, msg)) tpl = "%s\t%s\t%s" date_format = "%Y-%m-%d %H:%M:%S" cls = self.__class__.__name__ self.queue.put(tpl % (now.strftime(date_format), cls, msg)) class RcReader(object): def _has_line(self, lines, line_start): for line in lines: if line.startswith(line_start): return True return False def _get_rc_content(self): rc = None try: with open('/etc/rc.conf', 'r') as f: rc = f.readlines() except IOError: pass if not rc: raise RuntimeError("File `/etc/rc.conf` is empty!") return rc class EZJailTask(SetupTask, RcReader): ''' Setups ezjail in the virtual machine. ''' def run(self): try: self.log("Enabling EZJail.") self._enable_ezjail() self.log("Installing EZJail") EzJail().install(cherrypy.config.get('setup_plugin.ftp_mirror')) except (IOError, OSError) as e: self.log("Error while installing ezjail: %s" % e) return False return True def _enable_ezjail(self): rc = self._get_rc_content() if self._has_line(rc, 'ezjail_enable'): self.log("EZJail is already enabled.") return self.log("Adding to rc: `%s`" % 'ezjail_enable="YES"') '''if we get here, it means ezjail_enable is not in rc.conf''' with open('/etc/rc.conf', 'a') as f: f.write("ezjail_enable=\"YES\"\n") class SSHTask(SetupTask): '''Create the base user `puck` and add the authorized ssh keys''' def run(self): self._setup_ssh() return True def _setup_ssh(self): if not self.vm.keys: self.log("No keys to install."); return True #@TODO Could be moved to config values instead of hardcoded. user = 'puck' try: pwd.getpwnam(user) except KeyError as e: cmd = 'pw user add %s -m -G wheel' % user self.log("Adding user. Executing `%s`" % cmd) subprocess.Popen(shlex.split(str(cmd))).wait() user_pwd = pwd.getpwnam(user) path = '/home/%s/.ssh' % user authorized_file = "%s/authorized_keys" % path if not os.path.exists(path): os.mkdir(path) os.chown(path, user_pwd.pw_uid, user_pwd.pw_gid) with open(authorized_file, 'a') as f: for key in self.vm.keys: self.log("Writing key `%s`" % key) f.write('%s\n' % self.vm.keys[key]['key']) os.chmod(authorized_file, 0400) os.chown(authorized_file, user_pwd.pw_uid, user_pwd.pw_gid) os.chmod(path, 0700) os.chmod('/home/%s' % user, 0700) class FirewallSetupTask(SetupTask, RcReader): def run(self): # TODO Move this to a congfiguration value from puck. Not high priority pf_conf = '/etc/pf.rules.conf' rc_conf = '/etc/rc.conf' self.setup_rc(rc_conf, pf_conf) self.setup_pf_conf(pf_conf) self.launch_pf() return True def launch_pf(self): # Stop it in case it commands = ['/etc/rc.d/pf stop', '/etc/rc.d/pf start'] for command in commands: self.log("Executing: `%s`" % command) subprocess.Popen(shlex.split(str(command))).wait() def setup_pf_conf(self, pf_conf): rules = self.vm.firewall if not rules: self.log("No firewall to write.") return False self.log("Writing firewall rules at `%s`." % pf_conf) with open(pf_conf, 'w') as f: f.write(rules.replace('\r\n', '\n').replace('\r', '\n')) f.flush() def setup_rc(self, rc_conf, pf_conf): #TODO Move this to a configuration value. Not high priority. rc_items = { 'pf_enable' : 'YES', 'pf_rules' : pf_conf, 'pflog_enable' : 'YES', 'gateway_enable' : 'YES' } rc_present = [] rc = self._get_rc_content() for line in rc: for k in rc_items: if line.startswith(k): rc_present.append(k) break missing = set(rc_items.keys()) - set(rc_present) tpl = 'Adding to rc: `%s="%s"`' [self.log(tpl % (k, rc_items[k])) for k in missing] template = '%s="%s"\n' with open(rc_conf, 'a') as f: [f.write(template % (k,rc_items[k])) for k in missing] f.flush() class InterfacesSetupTask(SetupTask, RcReader): '''Configures network interfaces for the jails.''' def run(self): (netaddrs, missing) = self._get_missing_netaddrs() self._add_missing_netaddrs(missing) self._add_missing_rc(netaddrs) return True def _add_missing_rc(self, netaddrs): rc_addresses = [] rc = self._get_rc_content() alias_count = self._calculate_alias_count(rc_addresses, rc) with open('/etc/rc.conf', 'a') as f: for netaddr in netaddrs: if self._add_rc_ip(rc_addresses, f, alias_count, netaddr): alias_count += 1 def _add_missing_netaddrs(self, netaddrs): for netaddr in netaddrs: self.log("Registering new ip address `%s`" % netaddr['ip']) self._add_addr(netaddr['ip'], netaddr['netmask']) def _get_missing_netaddrs(self): interfaces = NetInterfaces.getInterfaces() missing = [] netaddrs = [] for jail in self.vm.jails: netaddr = {'ip': jail.ip, 'netmask': jail.netmask} netaddrs.append(netaddr) if not interfaces.has_key(jail.ip): missing.append(netaddr) return (netaddrs, missing) def _calculate_alias_count(self, addresses, rc): alias_count = 0 for line in rc: if line.startswith('ifconfig_%s_alias' % self.vm.interface): alias_count += 1 addresses.append(line) return alias_count def _add_addr(self, ip, netmask): cmd = "ifconfig %s alias %s netmask %s" command = cmd % (self.vm.interface, ip, netmask) self.log('executing: `%s`' % command) subprocess.Popen(shlex.split(str(command))).wait() def _add_rc_ip(self, rc_addresses, file, alias_count, netaddr): for item in rc_addresses: if item.find(netaddr['ip']) > 0: self.log("rc already knows about ip `%s`" % netaddr['ip']) return False self.log("Registering new rc value for ip `%s`" % netaddr['ip']) template = 'ifconfig_%s_alias%s="inet %s netmask %s"' line = "%s\n" % template values = ( self.vm.interface, alias_count, netaddr['ip'], netaddr['netmask'] ) file.write(line % values) file.flush() return True class HypervisorSetupTask(SetupTask, RcReader): ''' Setups a few hypervisor settings such as Shared Memory/IPC ''' def run(self): self._add_rc_settings() self._add_sysctl_settings() self._set_hostname() return True def _set_hostname(self): self.log("Replacing hostname in /etc/rc.conf") (fh, abspath) = tempfile.mkstemp() tmp = open(abspath, 'w') with open('/etc/rc.conf', 'r') as f: for line in f: if not line.startswith('hostname'): tmp.write(line) continue tmp.write('hostname="%s"\n' % self.vm.name) tmp.close() os.close(fh) os.remove('/etc/rc.conf') shutil.move(abspath, '/etc/rc.conf') os.chmod('/etc/rc.conf', 0644) cmd = str('hostname %s' % self.vm.name) self.log('Executing: `%s`' % cmd) subprocess.Popen(shlex.split(cmd)).wait() def _add_sysctl_settings(self): sysvipc = cherrypy.config.get('hypervisor.jail_sysvipc_allow') ipc_setting = 'security.jail.sysvipc_allowed' self.log("Configuring sysctl") with open('/etc/sysctl.conf', 'r') as f: sysctl = f.readlines() if sysvipc: cmd = str("sysctl %s=1" % ipc_setting) self.log('Executing: `%s`' % cmd) subprocess.Popen(shlex.split(cmd)).wait() if self._has_line(sysctl, ipc_setting): self.log('SysV IPC already configured in sysctl.conf') return template = '%s=%s\n' data = template % (ipc_setting, 1) self.log('Adding to sysctl.conf: `%s`' % data) with open('/etc/sysctl.conf', 'a') as f: f.write(data) def _add_rc_settings(self): items = [ 'jail_sysvipc_allow', 'syslogd_flags' ] rc = self._get_rc_content() # settings will contain items to be added to rc settings = {} for i in items: value = cherrypy.config.get('hypervisor.%s' % i) if not value: continue if self._has_line(rc, i): continue self.log('Adding to rc: `%s="%s"`' % (i, value)) settings[i] = value # settings now contains items to be added template = '%s="%s"\n' with open('/etc/rc.conf', 'a') as f: [f.write(template % (k, settings[k])) for k in settings] f.flush() class EZJailSetupTask(SetupTask): ''' Setups ezjail in the virtual machine ''' def run(self): base_dir = cherrypy.config.get('setup_plugin.jail_dir') dst_dir = '%s/flavours' % base_dir if not os.path.isdir(dst_dir): try: self.log("Creating folder `%s`." % dst_dir) os.makedirs(dst_dir) except OSError as e: self.log('Could not create folder `%s`' % dst_dir) return False # Holds the temporary file list tmpfiles = self._retrieveFlavours() if not tmpfiles: self.log('No flavours downloaded.') return False # Verify and extract the flavour tarball for file in tmpfiles: # Verify if not tarfile.is_tarfile(file['tmp_file']): msg = "File `%s` is not a tarfile." self.log(msg % file['tmp_file']) return False self.log('Extracting `%s`' % file['tmp_file']) # Extraction try: with tarfile.open(file['tmp_file'], mode='r:*') as t: '''Will raise KeyError if file does not exists.''' if not t.getmember(file['type']).isdir(): msg ="Tar member `%s` is not a folder." raise tarfile.ExtractError(msg % file['type']) t.extractall("%s/" % dst_dir) except (IOError, KeyError, tarfile.ExtractError) as e: msg = "File `%s` could not be extracted. Reason: %s" self.log(msg % (file['tmp_file'], e)) # Remove the temporary tarball try: os.unlink(file['tmp_file']) except OSerror as e: msg = "Error while removing file `%s`: %s" self.log(msg % (file['tmp_file'], e)) return True def _retrieveFlavours(self): '''Retrieve the tarball for each flavours''' tmpfiles = [] jail_dir = cherrypy.config.get('setup_plugin.jail_dir') for jail in self.vm.jails: (handle, tmpname) = tempfile.mkstemp(dir=jail_dir) self.log("Fetching flavour `%s` at `%s`" % (jail.name, jail.url)) try: (filename, headers) = urllib.urlretrieve(jail.url, tmpname) except (urllib.ContentTooShortError, IOError) as e: msg = "Error while retrieving jail `%s`: %s" self.log(msg % (jail.name, e)) return False tmpfiles.append({'type': jail.jail_type, 'tmp_file': filename}) self.log("Jail `%s` downloaded at `%s`" % (jail.name, filename)) return tmpfiles class JailConfigTask(SetupTask): ''' Handles jails configuration ''' def run(self): jail_dir = cherrypy.config.get('setup_plugin.jail_dir') flavour_dir = "%s/flavours" % jail_dir for jail in self.vm.jails: self.log("Configuring jail `%s`." % jail.jail_type) path = "%s/%s" % (flavour_dir, jail.jail_type) authorized_key_file = "%s/installdata/authorized_keys" % path resolv_file = "%s/etc/resolv.conf" % path yum_file = "%s/installdata/yum_repo" % path rc_file = "%s/etc/rc.conf" % path host_file = "%s/etc/hosts" % path # Create /installdata and /etc folder. for p in ['%s/installdata', '%s/etc']: if not os.path.exists(p % path): os.mkdir(p % path) # Verify the flavours exists. exists = os.path.exists(path) is_dir = os.path.isdir(path) if not exists or not is_dir: msg = "Flavour `%s` directory is missing in `%s." self.log(msg % (jail.jail_type, flavour_dir)) return False msg = "Retrieving yum repository for environment `%s`." self.log(msg % self.vm.environment) yum_repo = self._puck.getYumRepo(self.vm.environment) self.log("Writing ssh keys.") if not self._writeKeys(jail, authorized_key_file): return False self.log("Copying resolv.conf.") if not self._writeResolvConf(jail, resolv_file): return False self.log("Updating jail hostname to `%s-%s`" % (self.vm.name, jail.jail_type)) if not self._update_hostname(jail, rc_file, host_file): return False self.log("Writing yum repository.") if not self._writeYumRepoConf(yum_repo, yum_file): return False self.log("Creating jail.") if not self._createJail(jail): return False return True def _writeKeys(self, jail, authorized_key_file): '''Write authorized keys''' try: with open(authorized_key_file, 'w') as f: for key in self.vm.keys.values(): f.write("%s\n" % key['key']) except IOError as e: msg = "Error while writing authorized keys to jail `%s`: %s" self.log(msg % (jail.jail_type, e)) return False return True def _update_hostname(self, jail, rc_file, host_file): hostname = "%s-%s" % (self.vm.name, jail.jail_type) self.log("Replacing hostname in %s" % rc_file) (fh, abspath) = tempfile.mkstemp() has_hostname = False tmp = open(abspath, 'w') with open(rc_file, 'r') as f: for line in f: if not line.startswith('hostname'): tmp.write(line) continue tmp.write('hostname="%s"\n' % hostname) has_hostname = True if not has_hostname: tmp.write('hostname="%s"\n' % hostname) tmp.close() os.close(fh) os.remove(rc_file) shutil.move(abspath, rc_file) os.chmod(rc_file, 0644) self.log("Adding new hostname in %s" % host_file) (fh, abspath) = tempfile.mkstemp() has_hostname = False tmp = open(abspath, 'w') with open(host_file, 'r') as f: for line in f: if not line.startswith('127.0.0.1'): tmp.write(line) continue tmp.write('%s %s\n' % (line.replace('\n', ''), hostname)) tmp.close() os.close(fh) os.remove(host_file) shutil.move(abspath, host_file) os.chmod(host_file, 0644) return True def _writeResolvConf(self, jail, resolv_file): '''Copy resolv.conf''' try: shutil.copyfile('/etc/resolv.conf', resolv_file) except IOError as e: self.log("Error while copying host resolv file: %s" % e) return False return True def _writeYumRepoConf(self, yum_repo, yum_file): '''Setup yum repo.d file ezjail will use.''' try: with open(yum_file, 'w') as f: f.write(yum_repo['data']) except (KeyError, IOError) as e: self.log("Error while writing YUM repo data: %s" % e) return False return True def _createJail(self, jail): '''Create the jail''' try: jail.create() except OSError as e: msg = "Error while installing jail `%s`: %s" self.log(msg % (jail.jail_type, e)) return False return True class JailStartupTask(SetupTask): ''' Handles starting each jail. ''' def run(self): # Start each jail for jail in self.vm.jails: self.log("Starting jail `%s`" % jail.jail_type) try: status = jail.start() except OSError as e: self.log("Could not start jail `%s`: %s" % (jail.jail_type, e)) return False self.log("Jail status: %s" % status) self.log("Jail `%s` started" % jail.jail_type) if not jail.status(): self.log("Jail `%s` is not running!" % jail.jail_type) return False return True class SetupWorkerThread(threading.Thread):
class SetupPlugin(plugins.SimplePlugin): ''' Handles tasks related to virtual machine setup. The plugin launches a separate thread to asynchronously execute the tasks. ''' def __init__(self, puck, bus, freq=30.0): plugins.SimplePlugin.__init__(self, bus) self.freq = freq self._puck = puck self._queue = queue.Queue() self._workerQueue = queue.Queue() self.worker = None self.statuses = [] def start(self): self.bus.log('Starting up setup tasks') self.bus.subscribe('setup', self.switch) start.priority = 70 def stop(self): self.bus.log('Stopping down setup task.') self._setup_stop(); def switch(self, *args, **kwargs): ''' This is the task switchboard. Depending on the parameters received, it will execute the appropriate action. ''' if not 'action' in kwargs: self.log("Parameter `action` is missing.") return # Default task def default(**kwargs): return return { 'start': self._setup_start, 'stop': self._setup_stop, 'status': self._setup_status, 'clear': self._clear_status }.get(kwargs['action'], default)() def _clear_status(self, **kwargs): '''Clear the status list''' del(self.statuses[:]) def _setup_stop(self, **kwargs): self.bus.log("Received stop request.") if self.worker and self.worker.isAlive(): self.worker.stop() def _start_worker(self): self.worker = SetupWorkerThread( bus=self.bus, queue = self._queue, outqueue = self._workerQueue, puck = self._puck ) self.worker.start() def _setup_start(self, **kwargs): self.bus.log("Received start request.") # Start the worker if it is not running. if not self.worker: self._start_worker() if not self.worker.is_alive() and not self.worker.successful: self._start_worker() # @TODO: Persistence of the list when failure occurs. # or a state machine instead of a queue. for task in cherrypy.config.get('setup_plugin.tasks'): self._queue.put(task) def _setup_status(self, **kwargs): ''' Returns the current log queue and if the setup is running or not. ''' status = self._readQueue(self._workerQueue) while status: self.statuses.append(status) status = self._readQueue(self._workerQueue) if not self.worker or not self.worker.isAlive(): return (self.statuses, False) return (self.statuses, True) def _readQueue(self, q, blocking = True, timeout = 0.2): ''' Wraps code to read from a queue, including exception handling. ''' try: item = q.get(blocking, timeout) except queue.Empty: return None return item
""" Thread class with a stop() method. The thread itself has to check regularly for the stopped() condition. """ def __init__(self, bus, queue, outqueue, puck): super(self.__class__, self).__init__() self._stop = threading.Event() self.running = threading.Event() self.successful = False self.completed = False self._queue = queue self._bus = bus self._outqueue = outqueue self._puck = puck def stop(self): self._stop.set() def stopped(self): return self._stop.isSet() def _step(self): ''' Run a task @raise RuntimeError when the task failed to complete ''' # This will probably need to be wrapped in a try/catch. task = self._queue.get(True, 10)(self._puck, self._outqueue) loginfo = (self.__class__.__name__, task.__class__.__name__) task.log('Starting') if not task.run(): raise RuntimeError("%s error while running task `%s`" % loginfo) task.log('Completed') self._queue.task_done() def run(self): if self.completed: self._bus.log("%s had already been run." % self.__class__.__name__) return False if self.running.isSet(): self._bus.log("%s is already running." % self.__class__.__name__) return False self.running.set() self._bus.log("%s started." % self.__class__.__name__) try: while not self.stopped(): self._step() except RuntimeError as err: self._bus.log(str(err)) self._empty_queue() self._puck.getVM().status = 'setup_failed' self._puck.updateStatus() self.succesful = False self.completed = True return False except queue.Empty: pass self.completed = True self.sucessful = True self._puck.getVM().status = 'setup_complete' self._puck.updateStatus() self._outqueue.put("%s finished." % self.__class__.__name__) def _empty_queue(self): while not self._queue.empty(): try: self._queue.get(False) except queue.Empty: return
identifier_body
setup_plugin.py
''' Pixie: FreeBSD virtualization guest configuration client Copyright (C) 2011 The Hotel Communication Network inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import threading, Queue as queue, time, subprocess, shlex, datetime import urllib, tarfile, os, shutil, tempfile, pwd import cherrypy from cherrypy.process import wspbus, plugins from pixie.lib.jails import EzJail from pixie.lib.interfaces import NetInterfaces class SetupTask(object): def __init__(self, puck, queue): self.queue = queue self._puck = puck self.vm = puck.getVM() def run(self): raise NotImplementedError("`run` must be defined.") def log(self, msg): now = datetime.datetime.now() cherrypy.log("%s %s" % (self.__class__.__name__, msg)) tpl = "%s\t%s\t%s" date_format = "%Y-%m-%d %H:%M:%S" cls = self.__class__.__name__ self.queue.put(tpl % (now.strftime(date_format), cls, msg)) class RcReader(object): def _has_line(self, lines, line_start): for line in lines: if line.startswith(line_start): return True return False def _get_rc_content(self): rc = None try: with open('/etc/rc.conf', 'r') as f: rc = f.readlines() except IOError: pass if not rc: raise RuntimeError("File `/etc/rc.conf` is empty!") return rc class EZJailTask(SetupTask, RcReader): ''' Setups ezjail in the virtual machine. ''' def run(self): try: self.log("Enabling EZJail.") self._enable_ezjail() self.log("Installing EZJail") EzJail().install(cherrypy.config.get('setup_plugin.ftp_mirror')) except (IOError, OSError) as e: self.log("Error while installing ezjail: %s" % e) return False return True def _enable_ezjail(self): rc = self._get_rc_content() if self._has_line(rc, 'ezjail_enable'): self.log("EZJail is already enabled.") return self.log("Adding to rc: `%s`" % 'ezjail_enable="YES"') '''if we get here, it means ezjail_enable is not in rc.conf''' with open('/etc/rc.conf', 'a') as f: f.write("ezjail_enable=\"YES\"\n") class SSHTask(SetupTask): '''Create the base user `puck` and add the authorized ssh keys''' def run(self): self._setup_ssh() return True def _setup_ssh(self): if not self.vm.keys: self.log("No keys to install."); return True #@TODO Could be moved to config values instead of hardcoded. user = 'puck' try: pwd.getpwnam(user) except KeyError as e: cmd = 'pw user add %s -m -G wheel' % user self.log("Adding user. Executing `%s`" % cmd) subprocess.Popen(shlex.split(str(cmd))).wait() user_pwd = pwd.getpwnam(user) path = '/home/%s/.ssh' % user authorized_file = "%s/authorized_keys" % path if not os.path.exists(path): os.mkdir(path) os.chown(path, user_pwd.pw_uid, user_pwd.pw_gid) with open(authorized_file, 'a') as f: for key in self.vm.keys: self.log("Writing key `%s`" % key) f.write('%s\n' % self.vm.keys[key]['key']) os.chmod(authorized_file, 0400) os.chown(authorized_file, user_pwd.pw_uid, user_pwd.pw_gid) os.chmod(path, 0700) os.chmod('/home/%s' % user, 0700) class FirewallSetupTask(SetupTask, RcReader): def run(self): # TODO Move this to a congfiguration value from puck. Not high priority pf_conf = '/etc/pf.rules.conf' rc_conf = '/etc/rc.conf' self.setup_rc(rc_conf, pf_conf) self.setup_pf_conf(pf_conf) self.launch_pf() return True def launch_pf(self): # Stop it in case it commands = ['/etc/rc.d/pf stop', '/etc/rc.d/pf start'] for command in commands: self.log("Executing: `%s`" % command) subprocess.Popen(shlex.split(str(command))).wait() def setup_pf_conf(self, pf_conf): rules = self.vm.firewall if not rules: self.log("No firewall to write.") return False self.log("Writing firewall rules at `%s`." % pf_conf) with open(pf_conf, 'w') as f: f.write(rules.replace('\r\n', '\n').replace('\r', '\n')) f.flush() def setup_rc(self, rc_conf, pf_conf): #TODO Move this to a configuration value. Not high priority. rc_items = { 'pf_enable' : 'YES', 'pf_rules' : pf_conf, 'pflog_enable' : 'YES', 'gateway_enable' : 'YES' } rc_present = [] rc = self._get_rc_content() for line in rc: for k in rc_items:
missing = set(rc_items.keys()) - set(rc_present) tpl = 'Adding to rc: `%s="%s"`' [self.log(tpl % (k, rc_items[k])) for k in missing] template = '%s="%s"\n' with open(rc_conf, 'a') as f: [f.write(template % (k,rc_items[k])) for k in missing] f.flush() class InterfacesSetupTask(SetupTask, RcReader): '''Configures network interfaces for the jails.''' def run(self): (netaddrs, missing) = self._get_missing_netaddrs() self._add_missing_netaddrs(missing) self._add_missing_rc(netaddrs) return True def _add_missing_rc(self, netaddrs): rc_addresses = [] rc = self._get_rc_content() alias_count = self._calculate_alias_count(rc_addresses, rc) with open('/etc/rc.conf', 'a') as f: for netaddr in netaddrs: if self._add_rc_ip(rc_addresses, f, alias_count, netaddr): alias_count += 1 def _add_missing_netaddrs(self, netaddrs): for netaddr in netaddrs: self.log("Registering new ip address `%s`" % netaddr['ip']) self._add_addr(netaddr['ip'], netaddr['netmask']) def _get_missing_netaddrs(self): interfaces = NetInterfaces.getInterfaces() missing = [] netaddrs = [] for jail in self.vm.jails: netaddr = {'ip': jail.ip, 'netmask': jail.netmask} netaddrs.append(netaddr) if not interfaces.has_key(jail.ip): missing.append(netaddr) return (netaddrs, missing) def _calculate_alias_count(self, addresses, rc): alias_count = 0 for line in rc: if line.startswith('ifconfig_%s_alias' % self.vm.interface): alias_count += 1 addresses.append(line) return alias_count def _add_addr(self, ip, netmask): cmd = "ifconfig %s alias %s netmask %s" command = cmd % (self.vm.interface, ip, netmask) self.log('executing: `%s`' % command) subprocess.Popen(shlex.split(str(command))).wait() def _add_rc_ip(self, rc_addresses, file, alias_count, netaddr): for item in rc_addresses: if item.find(netaddr['ip']) > 0: self.log("rc already knows about ip `%s`" % netaddr['ip']) return False self.log("Registering new rc value for ip `%s`" % netaddr['ip']) template = 'ifconfig_%s_alias%s="inet %s netmask %s"' line = "%s\n" % template values = ( self.vm.interface, alias_count, netaddr['ip'], netaddr['netmask'] ) file.write(line % values) file.flush() return True class HypervisorSetupTask(SetupTask, RcReader): ''' Setups a few hypervisor settings such as Shared Memory/IPC ''' def run(self): self._add_rc_settings() self._add_sysctl_settings() self._set_hostname() return True def _set_hostname(self): self.log("Replacing hostname in /etc/rc.conf") (fh, abspath) = tempfile.mkstemp() tmp = open(abspath, 'w') with open('/etc/rc.conf', 'r') as f: for line in f: if not line.startswith('hostname'): tmp.write(line) continue tmp.write('hostname="%s"\n' % self.vm.name) tmp.close() os.close(fh) os.remove('/etc/rc.conf') shutil.move(abspath, '/etc/rc.conf') os.chmod('/etc/rc.conf', 0644) cmd = str('hostname %s' % self.vm.name) self.log('Executing: `%s`' % cmd) subprocess.Popen(shlex.split(cmd)).wait() def _add_sysctl_settings(self): sysvipc = cherrypy.config.get('hypervisor.jail_sysvipc_allow') ipc_setting = 'security.jail.sysvipc_allowed' self.log("Configuring sysctl") with open('/etc/sysctl.conf', 'r') as f: sysctl = f.readlines() if sysvipc: cmd = str("sysctl %s=1" % ipc_setting) self.log('Executing: `%s`' % cmd) subprocess.Popen(shlex.split(cmd)).wait() if self._has_line(sysctl, ipc_setting): self.log('SysV IPC already configured in sysctl.conf') return template = '%s=%s\n' data = template % (ipc_setting, 1) self.log('Adding to sysctl.conf: `%s`' % data) with open('/etc/sysctl.conf', 'a') as f: f.write(data) def _add_rc_settings(self): items = [ 'jail_sysvipc_allow', 'syslogd_flags' ] rc = self._get_rc_content() # settings will contain items to be added to rc settings = {} for i in items: value = cherrypy.config.get('hypervisor.%s' % i) if not value: continue if self._has_line(rc, i): continue self.log('Adding to rc: `%s="%s"`' % (i, value)) settings[i] = value # settings now contains items to be added template = '%s="%s"\n' with open('/etc/rc.conf', 'a') as f: [f.write(template % (k, settings[k])) for k in settings] f.flush() class EZJailSetupTask(SetupTask): ''' Setups ezjail in the virtual machine ''' def run(self): base_dir = cherrypy.config.get('setup_plugin.jail_dir') dst_dir = '%s/flavours' % base_dir if not os.path.isdir(dst_dir): try: self.log("Creating folder `%s`." % dst_dir) os.makedirs(dst_dir) except OSError as e: self.log('Could not create folder `%s`' % dst_dir) return False # Holds the temporary file list tmpfiles = self._retrieveFlavours() if not tmpfiles: self.log('No flavours downloaded.') return False # Verify and extract the flavour tarball for file in tmpfiles: # Verify if not tarfile.is_tarfile(file['tmp_file']): msg = "File `%s` is not a tarfile." self.log(msg % file['tmp_file']) return False self.log('Extracting `%s`' % file['tmp_file']) # Extraction try: with tarfile.open(file['tmp_file'], mode='r:*') as t: '''Will raise KeyError if file does not exists.''' if not t.getmember(file['type']).isdir(): msg ="Tar member `%s` is not a folder." raise tarfile.ExtractError(msg % file['type']) t.extractall("%s/" % dst_dir) except (IOError, KeyError, tarfile.ExtractError) as e: msg = "File `%s` could not be extracted. Reason: %s" self.log(msg % (file['tmp_file'], e)) # Remove the temporary tarball try: os.unlink(file['tmp_file']) except OSerror as e: msg = "Error while removing file `%s`: %s" self.log(msg % (file['tmp_file'], e)) return True def _retrieveFlavours(self): '''Retrieve the tarball for each flavours''' tmpfiles = [] jail_dir = cherrypy.config.get('setup_plugin.jail_dir') for jail in self.vm.jails: (handle, tmpname) = tempfile.mkstemp(dir=jail_dir) self.log("Fetching flavour `%s` at `%s`" % (jail.name, jail.url)) try: (filename, headers) = urllib.urlretrieve(jail.url, tmpname) except (urllib.ContentTooShortError, IOError) as e: msg = "Error while retrieving jail `%s`: %s" self.log(msg % (jail.name, e)) return False tmpfiles.append({'type': jail.jail_type, 'tmp_file': filename}) self.log("Jail `%s` downloaded at `%s`" % (jail.name, filename)) return tmpfiles class JailConfigTask(SetupTask): ''' Handles jails configuration ''' def run(self): jail_dir = cherrypy.config.get('setup_plugin.jail_dir') flavour_dir = "%s/flavours" % jail_dir for jail in self.vm.jails: self.log("Configuring jail `%s`." % jail.jail_type) path = "%s/%s" % (flavour_dir, jail.jail_type) authorized_key_file = "%s/installdata/authorized_keys" % path resolv_file = "%s/etc/resolv.conf" % path yum_file = "%s/installdata/yum_repo" % path rc_file = "%s/etc/rc.conf" % path host_file = "%s/etc/hosts" % path # Create /installdata and /etc folder. for p in ['%s/installdata', '%s/etc']: if not os.path.exists(p % path): os.mkdir(p % path) # Verify the flavours exists. exists = os.path.exists(path) is_dir = os.path.isdir(path) if not exists or not is_dir: msg = "Flavour `%s` directory is missing in `%s." self.log(msg % (jail.jail_type, flavour_dir)) return False msg = "Retrieving yum repository for environment `%s`." self.log(msg % self.vm.environment) yum_repo = self._puck.getYumRepo(self.vm.environment) self.log("Writing ssh keys.") if not self._writeKeys(jail, authorized_key_file): return False self.log("Copying resolv.conf.") if not self._writeResolvConf(jail, resolv_file): return False self.log("Updating jail hostname to `%s-%s`" % (self.vm.name, jail.jail_type)) if not self._update_hostname(jail, rc_file, host_file): return False self.log("Writing yum repository.") if not self._writeYumRepoConf(yum_repo, yum_file): return False self.log("Creating jail.") if not self._createJail(jail): return False return True def _writeKeys(self, jail, authorized_key_file): '''Write authorized keys''' try: with open(authorized_key_file, 'w') as f: for key in self.vm.keys.values(): f.write("%s\n" % key['key']) except IOError as e: msg = "Error while writing authorized keys to jail `%s`: %s" self.log(msg % (jail.jail_type, e)) return False return True def _update_hostname(self, jail, rc_file, host_file): hostname = "%s-%s" % (self.vm.name, jail.jail_type) self.log("Replacing hostname in %s" % rc_file) (fh, abspath) = tempfile.mkstemp() has_hostname = False tmp = open(abspath, 'w') with open(rc_file, 'r') as f: for line in f: if not line.startswith('hostname'): tmp.write(line) continue tmp.write('hostname="%s"\n' % hostname) has_hostname = True if not has_hostname: tmp.write('hostname="%s"\n' % hostname) tmp.close() os.close(fh) os.remove(rc_file) shutil.move(abspath, rc_file) os.chmod(rc_file, 0644) self.log("Adding new hostname in %s" % host_file) (fh, abspath) = tempfile.mkstemp() has_hostname = False tmp = open(abspath, 'w') with open(host_file, 'r') as f: for line in f: if not line.startswith('127.0.0.1'): tmp.write(line) continue tmp.write('%s %s\n' % (line.replace('\n', ''), hostname)) tmp.close() os.close(fh) os.remove(host_file) shutil.move(abspath, host_file) os.chmod(host_file, 0644) return True def _writeResolvConf(self, jail, resolv_file): '''Copy resolv.conf''' try: shutil.copyfile('/etc/resolv.conf', resolv_file) except IOError as e: self.log("Error while copying host resolv file: %s" % e) return False return True def _writeYumRepoConf(self, yum_repo, yum_file): '''Setup yum repo.d file ezjail will use.''' try: with open(yum_file, 'w') as f: f.write(yum_repo['data']) except (KeyError, IOError) as e: self.log("Error while writing YUM repo data: %s" % e) return False return True def _createJail(self, jail): '''Create the jail''' try: jail.create() except OSError as e: msg = "Error while installing jail `%s`: %s" self.log(msg % (jail.jail_type, e)) return False return True class JailStartupTask(SetupTask): ''' Handles starting each jail. ''' def run(self): # Start each jail for jail in self.vm.jails: self.log("Starting jail `%s`" % jail.jail_type) try: status = jail.start() except OSError as e: self.log("Could not start jail `%s`: %s" % (jail.jail_type, e)) return False self.log("Jail status: %s" % status) self.log("Jail `%s` started" % jail.jail_type) if not jail.status(): self.log("Jail `%s` is not running!" % jail.jail_type) return False return True class SetupWorkerThread(threading.Thread): """ Thread class with a stop() method. The thread itself has to check regularly for the stopped() condition. """ def __init__(self, bus, queue, outqueue, puck): super(self.__class__, self).__init__() self._stop = threading.Event() self.running = threading.Event() self.successful = False self.completed = False self._queue = queue self._bus = bus self._outqueue = outqueue self._puck = puck def stop(self): self._stop.set() def stopped(self): return self._stop.isSet() def _step(self): ''' Run a task @raise RuntimeError when the task failed to complete ''' # This will probably need to be wrapped in a try/catch. task = self._queue.get(True, 10)(self._puck, self._outqueue) loginfo = (self.__class__.__name__, task.__class__.__name__) task.log('Starting') if not task.run(): raise RuntimeError("%s error while running task `%s`" % loginfo) task.log('Completed') self._queue.task_done() def run(self): if self.completed: self._bus.log("%s had already been run." % self.__class__.__name__) return False if self.running.isSet(): self._bus.log("%s is already running." % self.__class__.__name__) return False self.running.set() self._bus.log("%s started." % self.__class__.__name__) try: while not self.stopped(): self._step() except RuntimeError as err: self._bus.log(str(err)) self._empty_queue() self._puck.getVM().status = 'setup_failed' self._puck.updateStatus() self.succesful = False self.completed = True return False except queue.Empty: pass self.completed = True self.sucessful = True self._puck.getVM().status = 'setup_complete' self._puck.updateStatus() self._outqueue.put("%s finished." % self.__class__.__name__) def _empty_queue(self): while not self._queue.empty(): try: self._queue.get(False) except queue.Empty: return class SetupPlugin(plugins.SimplePlugin): ''' Handles tasks related to virtual machine setup. The plugin launches a separate thread to asynchronously execute the tasks. ''' def __init__(self, puck, bus, freq=30.0): plugins.SimplePlugin.__init__(self, bus) self.freq = freq self._puck = puck self._queue = queue.Queue() self._workerQueue = queue.Queue() self.worker = None self.statuses = [] def start(self): self.bus.log('Starting up setup tasks') self.bus.subscribe('setup', self.switch) start.priority = 70 def stop(self): self.bus.log('Stopping down setup task.') self._setup_stop(); def switch(self, *args, **kwargs): ''' This is the task switchboard. Depending on the parameters received, it will execute the appropriate action. ''' if not 'action' in kwargs: self.log("Parameter `action` is missing.") return # Default task def default(**kwargs): return return { 'start': self._setup_start, 'stop': self._setup_stop, 'status': self._setup_status, 'clear': self._clear_status }.get(kwargs['action'], default)() def _clear_status(self, **kwargs): '''Clear the status list''' del(self.statuses[:]) def _setup_stop(self, **kwargs): self.bus.log("Received stop request.") if self.worker and self.worker.isAlive(): self.worker.stop() def _start_worker(self): self.worker = SetupWorkerThread( bus=self.bus, queue = self._queue, outqueue = self._workerQueue, puck = self._puck ) self.worker.start() def _setup_start(self, **kwargs): self.bus.log("Received start request.") # Start the worker if it is not running. if not self.worker: self._start_worker() if not self.worker.is_alive() and not self.worker.successful: self._start_worker() # @TODO: Persistence of the list when failure occurs. # or a state machine instead of a queue. for task in cherrypy.config.get('setup_plugin.tasks'): self._queue.put(task) def _setup_status(self, **kwargs): ''' Returns the current log queue and if the setup is running or not. ''' status = self._readQueue(self._workerQueue) while status: self.statuses.append(status) status = self._readQueue(self._workerQueue) if not self.worker or not self.worker.isAlive(): return (self.statuses, False) return (self.statuses, True) def _readQueue(self, q, blocking = True, timeout = 0.2): ''' Wraps code to read from a queue, including exception handling. ''' try: item = q.get(blocking, timeout) except queue.Empty: return None return item
if line.startswith(k): rc_present.append(k) break
conditional_block
setup_plugin.py
''' Pixie: FreeBSD virtualization guest configuration client Copyright (C) 2011 The Hotel Communication Network inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import threading, Queue as queue, time, subprocess, shlex, datetime import urllib, tarfile, os, shutil, tempfile, pwd import cherrypy from cherrypy.process import wspbus, plugins from pixie.lib.jails import EzJail from pixie.lib.interfaces import NetInterfaces class SetupTask(object): def __init__(self, puck, queue): self.queue = queue self._puck = puck self.vm = puck.getVM() def run(self): raise NotImplementedError("`run` must be defined.") def log(self, msg): now = datetime.datetime.now() cherrypy.log("%s %s" % (self.__class__.__name__, msg)) tpl = "%s\t%s\t%s" date_format = "%Y-%m-%d %H:%M:%S" cls = self.__class__.__name__ self.queue.put(tpl % (now.strftime(date_format), cls, msg)) class RcReader(object): def _has_line(self, lines, line_start): for line in lines: if line.startswith(line_start): return True return False def _get_rc_content(self): rc = None try: with open('/etc/rc.conf', 'r') as f: rc = f.readlines() except IOError: pass if not rc: raise RuntimeError("File `/etc/rc.conf` is empty!") return rc class EZJailTask(SetupTask, RcReader): ''' Setups ezjail in the virtual machine. ''' def run(self): try: self.log("Enabling EZJail.") self._enable_ezjail() self.log("Installing EZJail") EzJail().install(cherrypy.config.get('setup_plugin.ftp_mirror')) except (IOError, OSError) as e: self.log("Error while installing ezjail: %s" % e) return False return True def _enable_ezjail(self): rc = self._get_rc_content() if self._has_line(rc, 'ezjail_enable'): self.log("EZJail is already enabled.") return self.log("Adding to rc: `%s`" % 'ezjail_enable="YES"') '''if we get here, it means ezjail_enable is not in rc.conf''' with open('/etc/rc.conf', 'a') as f: f.write("ezjail_enable=\"YES\"\n") class SSHTask(SetupTask): '''Create the base user `puck` and add the authorized ssh keys''' def run(self): self._setup_ssh() return True def _setup_ssh(self): if not self.vm.keys: self.log("No keys to install."); return True #@TODO Could be moved to config values instead of hardcoded. user = 'puck' try: pwd.getpwnam(user) except KeyError as e: cmd = 'pw user add %s -m -G wheel' % user self.log("Adding user. Executing `%s`" % cmd) subprocess.Popen(shlex.split(str(cmd))).wait() user_pwd = pwd.getpwnam(user) path = '/home/%s/.ssh' % user authorized_file = "%s/authorized_keys" % path if not os.path.exists(path): os.mkdir(path) os.chown(path, user_pwd.pw_uid, user_pwd.pw_gid) with open(authorized_file, 'a') as f: for key in self.vm.keys: self.log("Writing key `%s`" % key) f.write('%s\n' % self.vm.keys[key]['key']) os.chmod(authorized_file, 0400) os.chown(authorized_file, user_pwd.pw_uid, user_pwd.pw_gid) os.chmod(path, 0700) os.chmod('/home/%s' % user, 0700) class FirewallSetupTask(SetupTask, RcReader): def run(self): # TODO Move this to a congfiguration value from puck. Not high priority pf_conf = '/etc/pf.rules.conf' rc_conf = '/etc/rc.conf' self.setup_rc(rc_conf, pf_conf) self.setup_pf_conf(pf_conf) self.launch_pf() return True def launch_pf(self): # Stop it in case it commands = ['/etc/rc.d/pf stop', '/etc/rc.d/pf start'] for command in commands: self.log("Executing: `%s`" % command) subprocess.Popen(shlex.split(str(command))).wait() def setup_pf_conf(self, pf_conf): rules = self.vm.firewall if not rules: self.log("No firewall to write.") return False self.log("Writing firewall rules at `%s`." % pf_conf) with open(pf_conf, 'w') as f: f.write(rules.replace('\r\n', '\n').replace('\r', '\n')) f.flush() def setup_rc(self, rc_conf, pf_conf): #TODO Move this to a configuration value. Not high priority. rc_items = { 'pf_enable' : 'YES', 'pf_rules' : pf_conf, 'pflog_enable' : 'YES', 'gateway_enable' : 'YES' } rc_present = [] rc = self._get_rc_content() for line in rc: for k in rc_items: if line.startswith(k): rc_present.append(k) break missing = set(rc_items.keys()) - set(rc_present) tpl = 'Adding to rc: `%s="%s"`' [self.log(tpl % (k, rc_items[k])) for k in missing] template = '%s="%s"\n' with open(rc_conf, 'a') as f: [f.write(template % (k,rc_items[k])) for k in missing] f.flush() class InterfacesSetupTask(SetupTask, RcReader): '''Configures network interfaces for the jails.''' def run(self): (netaddrs, missing) = self._get_missing_netaddrs() self._add_missing_netaddrs(missing) self._add_missing_rc(netaddrs) return True def _add_missing_rc(self, netaddrs): rc_addresses = [] rc = self._get_rc_content() alias_count = self._calculate_alias_count(rc_addresses, rc) with open('/etc/rc.conf', 'a') as f: for netaddr in netaddrs: if self._add_rc_ip(rc_addresses, f, alias_count, netaddr): alias_count += 1 def _add_missing_netaddrs(self, netaddrs): for netaddr in netaddrs: self.log("Registering new ip address `%s`" % netaddr['ip']) self._add_addr(netaddr['ip'], netaddr['netmask']) def _get_missing_netaddrs(self): interfaces = NetInterfaces.getInterfaces() missing = [] netaddrs = [] for jail in self.vm.jails: netaddr = {'ip': jail.ip, 'netmask': jail.netmask} netaddrs.append(netaddr) if not interfaces.has_key(jail.ip): missing.append(netaddr) return (netaddrs, missing) def _calculate_alias_count(self, addresses, rc): alias_count = 0 for line in rc: if line.startswith('ifconfig_%s_alias' % self.vm.interface): alias_count += 1 addresses.append(line) return alias_count def _add_addr(self, ip, netmask): cmd = "ifconfig %s alias %s netmask %s" command = cmd % (self.vm.interface, ip, netmask) self.log('executing: `%s`' % command) subprocess.Popen(shlex.split(str(command))).wait() def _add_rc_ip(self, rc_addresses, file, alias_count, netaddr): for item in rc_addresses: if item.find(netaddr['ip']) > 0: self.log("rc already knows about ip `%s`" % netaddr['ip']) return False self.log("Registering new rc value for ip `%s`" % netaddr['ip']) template = 'ifconfig_%s_alias%s="inet %s netmask %s"' line = "%s\n" % template values = ( self.vm.interface, alias_count, netaddr['ip'], netaddr['netmask'] ) file.write(line % values) file.flush() return True class HypervisorSetupTask(SetupTask, RcReader): ''' Setups a few hypervisor settings such as Shared Memory/IPC ''' def run(self): self._add_rc_settings() self._add_sysctl_settings() self._set_hostname() return True def _set_hostname(self): self.log("Replacing hostname in /etc/rc.conf") (fh, abspath) = tempfile.mkstemp() tmp = open(abspath, 'w') with open('/etc/rc.conf', 'r') as f: for line in f: if not line.startswith('hostname'): tmp.write(line) continue tmp.write('hostname="%s"\n' % self.vm.name) tmp.close() os.close(fh) os.remove('/etc/rc.conf') shutil.move(abspath, '/etc/rc.conf') os.chmod('/etc/rc.conf', 0644) cmd = str('hostname %s' % self.vm.name) self.log('Executing: `%s`' % cmd) subprocess.Popen(shlex.split(cmd)).wait() def _add_sysctl_settings(self): sysvipc = cherrypy.config.get('hypervisor.jail_sysvipc_allow') ipc_setting = 'security.jail.sysvipc_allowed' self.log("Configuring sysctl") with open('/etc/sysctl.conf', 'r') as f: sysctl = f.readlines() if sysvipc: cmd = str("sysctl %s=1" % ipc_setting) self.log('Executing: `%s`' % cmd) subprocess.Popen(shlex.split(cmd)).wait() if self._has_line(sysctl, ipc_setting): self.log('SysV IPC already configured in sysctl.conf') return template = '%s=%s\n' data = template % (ipc_setting, 1) self.log('Adding to sysctl.conf: `%s`' % data) with open('/etc/sysctl.conf', 'a') as f: f.write(data) def _add_rc_settings(self): items = [ 'jail_sysvipc_allow', 'syslogd_flags' ] rc = self._get_rc_content() # settings will contain items to be added to rc settings = {} for i in items: value = cherrypy.config.get('hypervisor.%s' % i) if not value: continue if self._has_line(rc, i): continue self.log('Adding to rc: `%s="%s"`' % (i, value)) settings[i] = value # settings now contains items to be added template = '%s="%s"\n' with open('/etc/rc.conf', 'a') as f: [f.write(template % (k, settings[k])) for k in settings] f.flush() class EZJailSetupTask(SetupTask): ''' Setups ezjail in the virtual machine ''' def run(self): base_dir = cherrypy.config.get('setup_plugin.jail_dir') dst_dir = '%s/flavours' % base_dir if not os.path.isdir(dst_dir): try: self.log("Creating folder `%s`." % dst_dir) os.makedirs(dst_dir) except OSError as e: self.log('Could not create folder `%s`' % dst_dir) return False # Holds the temporary file list tmpfiles = self._retrieveFlavours() if not tmpfiles: self.log('No flavours downloaded.') return False # Verify and extract the flavour tarball for file in tmpfiles: # Verify if not tarfile.is_tarfile(file['tmp_file']): msg = "File `%s` is not a tarfile." self.log(msg % file['tmp_file']) return False self.log('Extracting `%s`' % file['tmp_file']) # Extraction try: with tarfile.open(file['tmp_file'], mode='r:*') as t: '''Will raise KeyError if file does not exists.''' if not t.getmember(file['type']).isdir(): msg ="Tar member `%s` is not a folder." raise tarfile.ExtractError(msg % file['type']) t.extractall("%s/" % dst_dir) except (IOError, KeyError, tarfile.ExtractError) as e: msg = "File `%s` could not be extracted. Reason: %s" self.log(msg % (file['tmp_file'], e)) # Remove the temporary tarball try: os.unlink(file['tmp_file']) except OSerror as e: msg = "Error while removing file `%s`: %s" self.log(msg % (file['tmp_file'], e)) return True def _retrieveFlavours(self): '''Retrieve the tarball for each flavours''' tmpfiles = [] jail_dir = cherrypy.config.get('setup_plugin.jail_dir') for jail in self.vm.jails: (handle, tmpname) = tempfile.mkstemp(dir=jail_dir) self.log("Fetching flavour `%s` at `%s`" % (jail.name, jail.url)) try: (filename, headers) = urllib.urlretrieve(jail.url, tmpname) except (urllib.ContentTooShortError, IOError) as e: msg = "Error while retrieving jail `%s`: %s" self.log(msg % (jail.name, e)) return False tmpfiles.append({'type': jail.jail_type, 'tmp_file': filename}) self.log("Jail `%s` downloaded at `%s`" % (jail.name, filename)) return tmpfiles class JailConfigTask(SetupTask): ''' Handles jails configuration ''' def run(self): jail_dir = cherrypy.config.get('setup_plugin.jail_dir') flavour_dir = "%s/flavours" % jail_dir for jail in self.vm.jails: self.log("Configuring jail `%s`." % jail.jail_type) path = "%s/%s" % (flavour_dir, jail.jail_type) authorized_key_file = "%s/installdata/authorized_keys" % path resolv_file = "%s/etc/resolv.conf" % path yum_file = "%s/installdata/yum_repo" % path rc_file = "%s/etc/rc.conf" % path host_file = "%s/etc/hosts" % path # Create /installdata and /etc folder. for p in ['%s/installdata', '%s/etc']: if not os.path.exists(p % path): os.mkdir(p % path) # Verify the flavours exists. exists = os.path.exists(path) is_dir = os.path.isdir(path) if not exists or not is_dir: msg = "Flavour `%s` directory is missing in `%s." self.log(msg % (jail.jail_type, flavour_dir)) return False msg = "Retrieving yum repository for environment `%s`." self.log(msg % self.vm.environment) yum_repo = self._puck.getYumRepo(self.vm.environment) self.log("Writing ssh keys.") if not self._writeKeys(jail, authorized_key_file): return False self.log("Copying resolv.conf.") if not self._writeResolvConf(jail, resolv_file): return False self.log("Updating jail hostname to `%s-%s`" % (self.vm.name, jail.jail_type)) if not self._update_hostname(jail, rc_file, host_file): return False self.log("Writing yum repository.") if not self._writeYumRepoConf(yum_repo, yum_file): return False self.log("Creating jail.") if not self._createJail(jail): return False return True def _writeKeys(self, jail, authorized_key_file): '''Write authorized keys''' try: with open(authorized_key_file, 'w') as f: for key in self.vm.keys.values(): f.write("%s\n" % key['key']) except IOError as e: msg = "Error while writing authorized keys to jail `%s`: %s" self.log(msg % (jail.jail_type, e)) return False return True def _update_hostname(self, jail, rc_file, host_file): hostname = "%s-%s" % (self.vm.name, jail.jail_type) self.log("Replacing hostname in %s" % rc_file) (fh, abspath) = tempfile.mkstemp() has_hostname = False tmp = open(abspath, 'w') with open(rc_file, 'r') as f: for line in f: if not line.startswith('hostname'): tmp.write(line) continue tmp.write('hostname="%s"\n' % hostname) has_hostname = True if not has_hostname: tmp.write('hostname="%s"\n' % hostname) tmp.close() os.close(fh) os.remove(rc_file) shutil.move(abspath, rc_file) os.chmod(rc_file, 0644) self.log("Adding new hostname in %s" % host_file) (fh, abspath) = tempfile.mkstemp() has_hostname = False tmp = open(abspath, 'w') with open(host_file, 'r') as f: for line in f: if not line.startswith('127.0.0.1'): tmp.write(line) continue tmp.write('%s %s\n' % (line.replace('\n', ''), hostname)) tmp.close() os.close(fh) os.remove(host_file) shutil.move(abspath, host_file) os.chmod(host_file, 0644) return True def _writeResolvConf(self, jail, resolv_file): '''Copy resolv.conf''' try: shutil.copyfile('/etc/resolv.conf', resolv_file) except IOError as e: self.log("Error while copying host resolv file: %s" % e) return False return True def _writeYumRepoConf(self, yum_repo, yum_file): '''Setup yum repo.d file ezjail will use.''' try: with open(yum_file, 'w') as f: f.write(yum_repo['data']) except (KeyError, IOError) as e: self.log("Error while writing YUM repo data: %s" % e) return False return True def _createJail(self, jail): '''Create the jail''' try: jail.create() except OSError as e: msg = "Error while installing jail `%s`: %s" self.log(msg % (jail.jail_type, e)) return False return True class JailStartupTask(SetupTask): ''' Handles starting each jail. ''' def run(self): # Start each jail for jail in self.vm.jails: self.log("Starting jail `%s`" % jail.jail_type) try: status = jail.start() except OSError as e: self.log("Could not start jail `%s`: %s" % (jail.jail_type, e)) return False self.log("Jail status: %s" % status) self.log("Jail `%s` started" % jail.jail_type) if not jail.status(): self.log("Jail `%s` is not running!" % jail.jail_type) return False return True class SetupWorkerThread(threading.Thread): """ Thread class with a stop() method. The thread itself has to check regularly for the stopped() condition. """ def __init__(self, bus, queue, outqueue, puck): super(self.__class__, self).__init__() self._stop = threading.Event() self.running = threading.Event() self.successful = False self.completed = False self._queue = queue self._bus = bus self._outqueue = outqueue self._puck = puck def stop(self): self._stop.set() def stopped(self): return self._stop.isSet() def _step(self): ''' Run a task @raise RuntimeError when the task failed to complete ''' # This will probably need to be wrapped in a try/catch. task = self._queue.get(True, 10)(self._puck, self._outqueue) loginfo = (self.__class__.__name__, task.__class__.__name__) task.log('Starting') if not task.run(): raise RuntimeError("%s error while running task `%s`" % loginfo) task.log('Completed') self._queue.task_done() def run(self): if self.completed: self._bus.log("%s had already been run." % self.__class__.__name__) return False if self.running.isSet(): self._bus.log("%s is already running." % self.__class__.__name__) return False self.running.set() self._bus.log("%s started." % self.__class__.__name__) try: while not self.stopped(): self._step() except RuntimeError as err: self._bus.log(str(err)) self._empty_queue() self._puck.getVM().status = 'setup_failed' self._puck.updateStatus() self.succesful = False self.completed = True return False except queue.Empty: pass self.completed = True self.sucessful = True self._puck.getVM().status = 'setup_complete' self._puck.updateStatus() self._outqueue.put("%s finished." % self.__class__.__name__) def _empty_queue(self): while not self._queue.empty(): try: self._queue.get(False) except queue.Empty: return class SetupPlugin(plugins.SimplePlugin): ''' Handles tasks related to virtual machine setup. The plugin launches a separate thread to asynchronously execute the tasks. ''' def __init__(self, puck, bus, freq=30.0): plugins.SimplePlugin.__init__(self, bus) self.freq = freq self._puck = puck self._queue = queue.Queue() self._workerQueue = queue.Queue() self.worker = None self.statuses = [] def start(self): self.bus.log('Starting up setup tasks') self.bus.subscribe('setup', self.switch) start.priority = 70 def stop(self): self.bus.log('Stopping down setup task.') self._setup_stop(); def switch(self, *args, **kwargs): ''' This is the task switchboard. Depending on the parameters received, it will execute the appropriate action. ''' if not 'action' in kwargs: self.log("Parameter `action` is missing.") return # Default task def default(**kwargs): return return { 'start': self._setup_start, 'stop': self._setup_stop, 'status': self._setup_status, 'clear': self._clear_status }.get(kwargs['action'], default)() def _clear_status(self, **kwargs): '''Clear the status list''' del(self.statuses[:]) def _setup_stop(self, **kwargs): self.bus.log("Received stop request.")
if self.worker and self.worker.isAlive(): self.worker.stop() def _start_worker(self): self.worker = SetupWorkerThread( bus=self.bus, queue = self._queue, outqueue = self._workerQueue, puck = self._puck ) self.worker.start() def _setup_start(self, **kwargs): self.bus.log("Received start request.") # Start the worker if it is not running. if not self.worker: self._start_worker() if not self.worker.is_alive() and not self.worker.successful: self._start_worker() # @TODO: Persistence of the list when failure occurs. # or a state machine instead of a queue. for task in cherrypy.config.get('setup_plugin.tasks'): self._queue.put(task) def _setup_status(self, **kwargs): ''' Returns the current log queue and if the setup is running or not. ''' status = self._readQueue(self._workerQueue) while status: self.statuses.append(status) status = self._readQueue(self._workerQueue) if not self.worker or not self.worker.isAlive(): return (self.statuses, False) return (self.statuses, True) def _readQueue(self, q, blocking = True, timeout = 0.2): ''' Wraps code to read from a queue, including exception handling. ''' try: item = q.get(blocking, timeout) except queue.Empty: return None return item
random_line_split
riak_repl.py
import json import unicodedata from requests.exceptions import ConnectionError, Timeout from six import iteritems from datadog_checks.base import AgentCheck from datadog_checks.base.errors import CheckException class RiakReplCheck(AgentCheck): REPL_STATS = { "server_bytes_sent", "server_bytes_recv", "server_connects", "server_connect_errors", "server_fullsyncs", "client_bytes_sent", "client_bytes_recv", "client_connects", "client_connect_errors", "client_redirect", "objects_dropped_no_clients", "objects_dropped_no_leader", "objects_sent", "objects_forwarded", "elections_elected", "elections_leader_changed", "rt_source_errors", "rt_sink_errors", "rt_dirty", "realtime_send_kbps", "realtime_recv_kbps", "fullsync_send_kbps", "fullsync_recv_kbps", } REALTIME_QUEUE_STATS = {"percent_bytes_used", "bytes", "max_bytes", "overload_drops"} REALTIME_QUEUE_STATS_CONSUMERS = {"pending", "unacked", "drops", "errs"} REALTIME_SOURCE_CONN = {"hb_rtt", "sent_seq", "objects"} REALTIME_SINK_CONN = {"deactivated", "source_drops", "expect_seq", "acked_seq", "pending"} FULLSYNC_COORDINATOR = { "queued", "in_progress", "waiting_for_retry", "starting", "successful_exits", "error_exits", "retry_exits", "soft_retry_exits", "busy_nodes", "fullsyncs_completed", "last_fullsync_duration", } def check(self, instance): url = instance.get('url', '') connected_clusters = instance.get('connected_clusters', '') tags = instance.get('tags', []) if not url: raise CheckException("Configuration error, please fix conf.yaml") try: r = self.http.get(url) except Timeout: raise CheckException('URL: {} timed out after {} seconds.'.format(url, self.http.options['timeout'])) except ConnectionError as e: raise CheckException(e) if r.status_code != 200: raise CheckException('Invalid Status Code, {} returned a status of {}.'.format(url, r.status_code)) try: stats = json.loads(r.text) except ValueError: raise CheckException('{} returned an unserializable payload'.format(url)) cluster = stats['cluster_name'] for key, val in iteritems(stats): if key in self.REPL_STATS: self.safe_submit_metric("riak_repl." + key, val, tags=tags + ['cluster:%s' % cluster]) if stats['realtime_started'] is not None: for key, val in iteritems(stats['realtime_queue_stats']): if key in self.REALTIME_QUEUE_STATS: self.safe_submit_metric( "riak_repl.realtime_queue_stats." + key, val, tags=tags + ['cluster:%s' % cluster] ) for c in connected_clusters: if stats['fullsync_enabled'] is not None: if self.exists(stats['fullsync_coordinator'], [c]): for key, val in iteritems(stats['fullsync_coordinator'][c]): if key in self.FULLSYNC_COORDINATOR: self.safe_submit_metric( "riak_repl.fullsync_coordinator." + key, val, tags=tags + ['cluster:%s' % c] ) if stats['realtime_started'] is not None: if self.exists(stats['sources'], ['source_stats', 'rt_source_connected_to']): for key, val in iteritems(stats['sources']['source_stats']['rt_source_connected_to']): if key in self.REALTIME_SOURCE_CONN: self.safe_submit_metric( "riak_repl.realtime_source.connected." + key, val, tags=tags + ['cluster:%s' % c] ) if self.exists(stats['realtime_queue_stats'], ['consumers', c]): for key, val in iteritems(stats['realtime_queue_stats']['consumers'][c]): if key in self.REALTIME_QUEUE_STATS_CONSUMERS: self.safe_submit_metric( "riak_repl.realtime_queue_stats.consumers." + key, val, tags=tags + ['cluster:%s' % c] ) if ( self.exists(stats['sinks'], ['sink_stats', 'rt_sink_connected_to']) and type(stats['sinks']['sink_stats']['rt_sink_connected_to']) is dict ): for key, val in iteritems(stats['sinks']['sink_stats']['rt_sink_connected_to']): if key in self.REALTIME_SINK_CONN: self.safe_submit_metric( "riak_repl.realtime_sink.connected." + key, val, tags=tags + ['cluster:%s' % c] ) def safe_submit_metric(self, name, value, tags=None): tags = [] if tags is None else tags try: self.gauge(name, float(value), tags=tags) return except ValueError: self.log.debug("metric name %s cannot be converted to a float: %s", name, value) try: self.gauge(name, unicodedata.numeric(value), tags=tags) return except (TypeError, ValueError): self.log.debug("metric name %s cannot be converted to a float even using unicode tools: %s", name, value) def exists(self, obj, nest): _key = nest.pop(0) if _key in obj:
return self.exists(obj[_key], nest) if nest else obj[_key]
conditional_block
riak_repl.py
import json import unicodedata from requests.exceptions import ConnectionError, Timeout from six import iteritems from datadog_checks.base import AgentCheck from datadog_checks.base.errors import CheckException class
(AgentCheck): REPL_STATS = { "server_bytes_sent", "server_bytes_recv", "server_connects", "server_connect_errors", "server_fullsyncs", "client_bytes_sent", "client_bytes_recv", "client_connects", "client_connect_errors", "client_redirect", "objects_dropped_no_clients", "objects_dropped_no_leader", "objects_sent", "objects_forwarded", "elections_elected", "elections_leader_changed", "rt_source_errors", "rt_sink_errors", "rt_dirty", "realtime_send_kbps", "realtime_recv_kbps", "fullsync_send_kbps", "fullsync_recv_kbps", } REALTIME_QUEUE_STATS = {"percent_bytes_used", "bytes", "max_bytes", "overload_drops"} REALTIME_QUEUE_STATS_CONSUMERS = {"pending", "unacked", "drops", "errs"} REALTIME_SOURCE_CONN = {"hb_rtt", "sent_seq", "objects"} REALTIME_SINK_CONN = {"deactivated", "source_drops", "expect_seq", "acked_seq", "pending"} FULLSYNC_COORDINATOR = { "queued", "in_progress", "waiting_for_retry", "starting", "successful_exits", "error_exits", "retry_exits", "soft_retry_exits", "busy_nodes", "fullsyncs_completed", "last_fullsync_duration", } def check(self, instance): url = instance.get('url', '') connected_clusters = instance.get('connected_clusters', '') tags = instance.get('tags', []) if not url: raise CheckException("Configuration error, please fix conf.yaml") try: r = self.http.get(url) except Timeout: raise CheckException('URL: {} timed out after {} seconds.'.format(url, self.http.options['timeout'])) except ConnectionError as e: raise CheckException(e) if r.status_code != 200: raise CheckException('Invalid Status Code, {} returned a status of {}.'.format(url, r.status_code)) try: stats = json.loads(r.text) except ValueError: raise CheckException('{} returned an unserializable payload'.format(url)) cluster = stats['cluster_name'] for key, val in iteritems(stats): if key in self.REPL_STATS: self.safe_submit_metric("riak_repl." + key, val, tags=tags + ['cluster:%s' % cluster]) if stats['realtime_started'] is not None: for key, val in iteritems(stats['realtime_queue_stats']): if key in self.REALTIME_QUEUE_STATS: self.safe_submit_metric( "riak_repl.realtime_queue_stats." + key, val, tags=tags + ['cluster:%s' % cluster] ) for c in connected_clusters: if stats['fullsync_enabled'] is not None: if self.exists(stats['fullsync_coordinator'], [c]): for key, val in iteritems(stats['fullsync_coordinator'][c]): if key in self.FULLSYNC_COORDINATOR: self.safe_submit_metric( "riak_repl.fullsync_coordinator." + key, val, tags=tags + ['cluster:%s' % c] ) if stats['realtime_started'] is not None: if self.exists(stats['sources'], ['source_stats', 'rt_source_connected_to']): for key, val in iteritems(stats['sources']['source_stats']['rt_source_connected_to']): if key in self.REALTIME_SOURCE_CONN: self.safe_submit_metric( "riak_repl.realtime_source.connected." + key, val, tags=tags + ['cluster:%s' % c] ) if self.exists(stats['realtime_queue_stats'], ['consumers', c]): for key, val in iteritems(stats['realtime_queue_stats']['consumers'][c]): if key in self.REALTIME_QUEUE_STATS_CONSUMERS: self.safe_submit_metric( "riak_repl.realtime_queue_stats.consumers." + key, val, tags=tags + ['cluster:%s' % c] ) if ( self.exists(stats['sinks'], ['sink_stats', 'rt_sink_connected_to']) and type(stats['sinks']['sink_stats']['rt_sink_connected_to']) is dict ): for key, val in iteritems(stats['sinks']['sink_stats']['rt_sink_connected_to']): if key in self.REALTIME_SINK_CONN: self.safe_submit_metric( "riak_repl.realtime_sink.connected." + key, val, tags=tags + ['cluster:%s' % c] ) def safe_submit_metric(self, name, value, tags=None): tags = [] if tags is None else tags try: self.gauge(name, float(value), tags=tags) return except ValueError: self.log.debug("metric name %s cannot be converted to a float: %s", name, value) try: self.gauge(name, unicodedata.numeric(value), tags=tags) return except (TypeError, ValueError): self.log.debug("metric name %s cannot be converted to a float even using unicode tools: %s", name, value) def exists(self, obj, nest): _key = nest.pop(0) if _key in obj: return self.exists(obj[_key], nest) if nest else obj[_key]
RiakReplCheck
identifier_name
riak_repl.py
import json import unicodedata from requests.exceptions import ConnectionError, Timeout from six import iteritems from datadog_checks.base import AgentCheck from datadog_checks.base.errors import CheckException class RiakReplCheck(AgentCheck): REPL_STATS = { "server_bytes_sent", "server_bytes_recv", "server_connects", "server_connect_errors", "server_fullsyncs", "client_bytes_sent", "client_bytes_recv", "client_connects", "client_connect_errors", "client_redirect", "objects_dropped_no_clients", "objects_dropped_no_leader", "objects_sent", "objects_forwarded", "elections_elected", "elections_leader_changed", "rt_source_errors", "rt_sink_errors", "rt_dirty", "realtime_send_kbps", "realtime_recv_kbps", "fullsync_send_kbps", "fullsync_recv_kbps", } REALTIME_QUEUE_STATS = {"percent_bytes_used", "bytes", "max_bytes", "overload_drops"} REALTIME_QUEUE_STATS_CONSUMERS = {"pending", "unacked", "drops", "errs"} REALTIME_SOURCE_CONN = {"hb_rtt", "sent_seq", "objects"} REALTIME_SINK_CONN = {"deactivated", "source_drops", "expect_seq", "acked_seq", "pending"} FULLSYNC_COORDINATOR = { "queued", "in_progress", "waiting_for_retry", "starting", "successful_exits", "error_exits", "retry_exits", "soft_retry_exits", "busy_nodes", "fullsyncs_completed", "last_fullsync_duration", } def check(self, instance): url = instance.get('url', '') connected_clusters = instance.get('connected_clusters', '') tags = instance.get('tags', []) if not url: raise CheckException("Configuration error, please fix conf.yaml") try: r = self.http.get(url) except Timeout: raise CheckException('URL: {} timed out after {} seconds.'.format(url, self.http.options['timeout'])) except ConnectionError as e: raise CheckException(e) if r.status_code != 200: raise CheckException('Invalid Status Code, {} returned a status of {}.'.format(url, r.status_code)) try: stats = json.loads(r.text) except ValueError: raise CheckException('{} returned an unserializable payload'.format(url)) cluster = stats['cluster_name'] for key, val in iteritems(stats): if key in self.REPL_STATS: self.safe_submit_metric("riak_repl." + key, val, tags=tags + ['cluster:%s' % cluster]) if stats['realtime_started'] is not None: for key, val in iteritems(stats['realtime_queue_stats']): if key in self.REALTIME_QUEUE_STATS: self.safe_submit_metric( "riak_repl.realtime_queue_stats." + key, val, tags=tags + ['cluster:%s' % cluster] ) for c in connected_clusters: if stats['fullsync_enabled'] is not None: if self.exists(stats['fullsync_coordinator'], [c]): for key, val in iteritems(stats['fullsync_coordinator'][c]): if key in self.FULLSYNC_COORDINATOR: self.safe_submit_metric( "riak_repl.fullsync_coordinator." + key, val, tags=tags + ['cluster:%s' % c] ) if stats['realtime_started'] is not None: if self.exists(stats['sources'], ['source_stats', 'rt_source_connected_to']): for key, val in iteritems(stats['sources']['source_stats']['rt_source_connected_to']): if key in self.REALTIME_SOURCE_CONN: self.safe_submit_metric( "riak_repl.realtime_source.connected." + key, val, tags=tags + ['cluster:%s' % c] ) if self.exists(stats['realtime_queue_stats'], ['consumers', c]): for key, val in iteritems(stats['realtime_queue_stats']['consumers'][c]): if key in self.REALTIME_QUEUE_STATS_CONSUMERS: self.safe_submit_metric( "riak_repl.realtime_queue_stats.consumers." + key, val, tags=tags + ['cluster:%s' % c] ) if ( self.exists(stats['sinks'], ['sink_stats', 'rt_sink_connected_to']) and type(stats['sinks']['sink_stats']['rt_sink_connected_to']) is dict ): for key, val in iteritems(stats['sinks']['sink_stats']['rt_sink_connected_to']): if key in self.REALTIME_SINK_CONN: self.safe_submit_metric( "riak_repl.realtime_sink.connected." + key, val, tags=tags + ['cluster:%s' % c] ) def safe_submit_metric(self, name, value, tags=None):
def exists(self, obj, nest): _key = nest.pop(0) if _key in obj: return self.exists(obj[_key], nest) if nest else obj[_key]
tags = [] if tags is None else tags try: self.gauge(name, float(value), tags=tags) return except ValueError: self.log.debug("metric name %s cannot be converted to a float: %s", name, value) try: self.gauge(name, unicodedata.numeric(value), tags=tags) return except (TypeError, ValueError): self.log.debug("metric name %s cannot be converted to a float even using unicode tools: %s", name, value)
identifier_body
riak_repl.py
import json import unicodedata from requests.exceptions import ConnectionError, Timeout from six import iteritems from datadog_checks.base import AgentCheck from datadog_checks.base.errors import CheckException class RiakReplCheck(AgentCheck): REPL_STATS = { "server_bytes_sent", "server_bytes_recv", "server_connects", "server_connect_errors", "server_fullsyncs", "client_bytes_sent", "client_bytes_recv", "client_connects", "client_connect_errors", "client_redirect", "objects_dropped_no_clients", "objects_dropped_no_leader", "objects_sent", "objects_forwarded", "elections_elected", "elections_leader_changed", "rt_source_errors", "rt_sink_errors", "rt_dirty", "realtime_send_kbps", "realtime_recv_kbps", "fullsync_send_kbps", "fullsync_recv_kbps", } REALTIME_QUEUE_STATS = {"percent_bytes_used", "bytes", "max_bytes", "overload_drops"} REALTIME_QUEUE_STATS_CONSUMERS = {"pending", "unacked", "drops", "errs"} REALTIME_SOURCE_CONN = {"hb_rtt", "sent_seq", "objects"} REALTIME_SINK_CONN = {"deactivated", "source_drops", "expect_seq", "acked_seq", "pending"} FULLSYNC_COORDINATOR = { "queued", "in_progress", "waiting_for_retry", "starting", "successful_exits", "error_exits", "retry_exits", "soft_retry_exits", "busy_nodes", "fullsyncs_completed", "last_fullsync_duration", } def check(self, instance): url = instance.get('url', '') connected_clusters = instance.get('connected_clusters', '') tags = instance.get('tags', []) if not url: raise CheckException("Configuration error, please fix conf.yaml") try: r = self.http.get(url) except Timeout: raise CheckException('URL: {} timed out after {} seconds.'.format(url, self.http.options['timeout'])) except ConnectionError as e: raise CheckException(e) if r.status_code != 200: raise CheckException('Invalid Status Code, {} returned a status of {}.'.format(url, r.status_code)) try: stats = json.loads(r.text) except ValueError: raise CheckException('{} returned an unserializable payload'.format(url))
if stats['realtime_started'] is not None: for key, val in iteritems(stats['realtime_queue_stats']): if key in self.REALTIME_QUEUE_STATS: self.safe_submit_metric( "riak_repl.realtime_queue_stats." + key, val, tags=tags + ['cluster:%s' % cluster] ) for c in connected_clusters: if stats['fullsync_enabled'] is not None: if self.exists(stats['fullsync_coordinator'], [c]): for key, val in iteritems(stats['fullsync_coordinator'][c]): if key in self.FULLSYNC_COORDINATOR: self.safe_submit_metric( "riak_repl.fullsync_coordinator." + key, val, tags=tags + ['cluster:%s' % c] ) if stats['realtime_started'] is not None: if self.exists(stats['sources'], ['source_stats', 'rt_source_connected_to']): for key, val in iteritems(stats['sources']['source_stats']['rt_source_connected_to']): if key in self.REALTIME_SOURCE_CONN: self.safe_submit_metric( "riak_repl.realtime_source.connected." + key, val, tags=tags + ['cluster:%s' % c] ) if self.exists(stats['realtime_queue_stats'], ['consumers', c]): for key, val in iteritems(stats['realtime_queue_stats']['consumers'][c]): if key in self.REALTIME_QUEUE_STATS_CONSUMERS: self.safe_submit_metric( "riak_repl.realtime_queue_stats.consumers." + key, val, tags=tags + ['cluster:%s' % c] ) if ( self.exists(stats['sinks'], ['sink_stats', 'rt_sink_connected_to']) and type(stats['sinks']['sink_stats']['rt_sink_connected_to']) is dict ): for key, val in iteritems(stats['sinks']['sink_stats']['rt_sink_connected_to']): if key in self.REALTIME_SINK_CONN: self.safe_submit_metric( "riak_repl.realtime_sink.connected." + key, val, tags=tags + ['cluster:%s' % c] ) def safe_submit_metric(self, name, value, tags=None): tags = [] if tags is None else tags try: self.gauge(name, float(value), tags=tags) return except ValueError: self.log.debug("metric name %s cannot be converted to a float: %s", name, value) try: self.gauge(name, unicodedata.numeric(value), tags=tags) return except (TypeError, ValueError): self.log.debug("metric name %s cannot be converted to a float even using unicode tools: %s", name, value) def exists(self, obj, nest): _key = nest.pop(0) if _key in obj: return self.exists(obj[_key], nest) if nest else obj[_key]
cluster = stats['cluster_name'] for key, val in iteritems(stats): if key in self.REPL_STATS: self.safe_submit_metric("riak_repl." + key, val, tags=tags + ['cluster:%s' % cluster])
random_line_split
macros.rs
// Copyright 2014 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. //! Standard library macros //! //! This modules contains a set of macros which are exported from the standard //! library. Each macro is available for use when linking against the standard //! library. /// The entry point for panic of Rust threads. /// /// This macro is used to inject panic into a Rust thread, causing the thread to /// unwind and panic entirely. Each thread's panic can be reaped as the /// `Box<Any>` type, and the single-argument form of the `panic!` macro will be /// the value which is transmitted. /// /// The multi-argument form of this macro panics with a string and has the /// `format!` syntax for building a string. /// /// # Examples /// /// ```should_panic /// # #![allow(unreachable_code)] /// panic!(); /// panic!("this is a terrible mistake!"); /// panic!(4); // panic with the value of 4 to be collected elsewhere /// panic!("this is a {} {message}", "fancy", message = "message"); /// ``` #[macro_export] #[allow_internal_unstable] macro_rules! panic { () => ({ panic!("explicit panic") }); ($msg:expr) => ({ $crate::rt::begin_unwind($msg, { // static requires less code at runtime, more constant data static _FILE_LINE: (&'static str, u32) = (file!(), line!()); &_FILE_LINE }) }); ($fmt:expr, $($arg:tt)+) => ({ $crate::rt::begin_unwind_fmt(format_args!($fmt, $($arg)+), { // The leading _'s are to avoid dead code warnings if this is // used inside a dead function. Just `#[allow(dead_code)]` is // insufficient, since the user may have // `#[forbid(dead_code)]` and which cannot be overridden. static _FILE_LINE: (&'static str, u32) = (file!(), line!()); &_FILE_LINE }) }); } /// Macro for printing to the standard output. /// /// Equivalent to the `println!` macro except that a newline is not printed at /// the end of the message. /// /// Note that stdout is frequently line-buffered by default so it may be /// necessary to use `io::stdout().flush()` to ensure the output is emitted /// immediately. /// /// # Panics /// /// Panics if writing to `io::stdout()` fails. /// /// # Examples /// /// ``` /// use std::io::{self, Write}; /// /// print!("this "); /// print!("will "); /// print!("be "); /// print!("on "); /// print!("the "); /// print!("same "); /// print!("line "); /// /// io::stdout().flush().unwrap(); /// /// print!("this string has a newline, why not choose println! instead?\n"); /// /// io::stdout().flush().unwrap(); /// ``` #[macro_export] #[allow_internal_unstable] macro_rules! print { ($($arg:tt)*) => ($crate::io::_print(format_args!($($arg)*))); } /// Macro for printing to the standard output, with a newline. /// /// Use the `format!` syntax to write data to the standard output. /// See `std::fmt` for more information. /// /// # Panics /// /// Panics if writing to `io::stdout()` fails. /// /// # Examples /// /// ``` /// println!("hello there!"); /// println!("format {} arguments", "some"); /// ``` #[macro_export] macro_rules! println { ($fmt:expr) => (print!(concat!($fmt, "\n"))); ($fmt:expr, $($arg:tt)*) => (print!(concat!($fmt, "\n"), $($arg)*)); } /// Helper macro for unwrapping `Result` values while returning early with an /// error if the value of the expression is `Err`. Can only be used in /// functions that return `Result` because of the early return of `Err` that /// it provides. /// /// # Examples /// /// ``` /// use std::io; /// use std::fs::File; /// use std::io::prelude::*; /// /// fn write_to_file_using_try() -> Result<(), io::Error> { /// let mut file = try!(File::create("my_best_friends.txt")); /// try!(file.write_all(b"This is a list of my best friends.")); /// println!("I wrote to the file"); /// Ok(()) /// } /// // This is equivalent to: /// fn write_to_file_using_match() -> Result<(), io::Error> { /// let mut file = try!(File::create("my_best_friends.txt")); /// match file.write_all(b"This is a list of my best friends.") { /// Ok(_) => (), /// Err(e) => return Err(e), /// } /// println!("I wrote to the file"); /// Ok(()) /// } /// ``` #[macro_export] macro_rules! try { ($expr:expr) => (match $expr { $crate::result::Result::Ok(val) => val, $crate::result::Result::Err(err) => { return $crate::result::Result::Err($crate::convert::From::from(err)) } }) } /// A macro to select an event from a number of receivers. /// /// This macro is used to wait for the first event to occur on a number of /// receivers. It places no restrictions on the types of receivers given to /// this macro, this can be viewed as a heterogeneous select. /// /// # Examples /// /// ``` /// #![feature(mpsc_select)] /// /// use std::thread; /// use std::sync::mpsc; /// /// // two placeholder functions for now /// fn long_running_thread() {} /// fn calculate_the_answer() -> u32 { 42 } /// /// let (tx1, rx1) = mpsc::channel(); /// let (tx2, rx2) = mpsc::channel(); /// /// thread::spawn(move|| { long_running_thread(); tx1.send(()).unwrap(); }); /// thread::spawn(move|| { tx2.send(calculate_the_answer()).unwrap(); }); /// /// select! { /// _ = rx1.recv() => println!("the long running thread finished first"), /// answer = rx2.recv() => { /// println!("the answer was: {}", answer.unwrap()); /// } /// } /// # drop(rx1.recv()); /// # drop(rx2.recv()); /// ``` /// /// For more information about select, see the `std::sync::mpsc::Select` structure. #[macro_export] macro_rules! select { ( $($name:pat = $rx:ident.$meth:ident() => $code:expr),+ ) => ({ use $crate::sync::mpsc::Select; let sel = Select::new(); $( let mut $rx = sel.handle(&$rx); )+ unsafe { $( $rx.add(); )+ } let ret = sel.wait(); $( if ret == $rx.id() { let $name = $rx.$meth(); $code } else )+ { unreachable!() } }) } // When testing the standard library, we link to the liblog crate to get the // logging macros. In doing so, the liblog crate was linked against the real // version of libstd, and uses a different std::fmt module than the test crate // uses. To get around this difference, we redefine the log!() macro here to be // just a dumb version of what it should be.
#[cfg(test)] macro_rules! log { ($lvl:expr, $($args:tt)*) => ( if log_enabled!($lvl) { println!($($args)*) } ) } #[cfg(test)] macro_rules! assert_approx_eq { ($a:expr, $b:expr) => ({ let (a, b) = (&$a, &$b); assert!((*a - *b).abs() < 1.0e-6, "{} is not approximately equal to {}", *a, *b); }) } /// Built-in macros to the compiler itself. /// /// These macros do not have any corresponding definition with a `macro_rules!` /// macro, but are documented here. Their implementations can be found hardcoded /// into libsyntax itself. #[cfg(dox)] pub mod builtin { /// The core macro for formatted string creation & output. /// /// This macro produces a value of type `fmt::Arguments`. This value can be /// passed to the functions in `std::fmt` for performing useful functions. /// All other formatting macros (`format!`, `write!`, `println!`, etc) are /// proxied through this one. /// /// For more information, see the documentation in `std::fmt`. /// /// # Examples /// /// ``` /// use std::fmt; /// /// let s = fmt::format(format_args!("hello {}", "world")); /// assert_eq!(s, format!("hello {}", "world")); /// /// ``` #[macro_export] macro_rules! format_args { ($fmt:expr, $($args:tt)*) => ({ /* compiler built-in */ }) } /// Inspect an environment variable at compile time. /// /// This macro will expand to the value of the named environment variable at /// compile time, yielding an expression of type `&'static str`. /// /// If the environment variable is not defined, then a compilation error /// will be emitted. To not emit a compile error, use the `option_env!` /// macro instead. /// /// # Examples /// /// ``` /// let path: &'static str = env!("PATH"); /// println!("the $PATH variable at the time of compiling was: {}", path); /// ``` #[macro_export] macro_rules! env { ($name:expr) => ({ /* compiler built-in */ }) } /// Optionally inspect an environment variable at compile time. /// /// If the named environment variable is present at compile time, this will /// expand into an expression of type `Option<&'static str>` whose value is /// `Some` of the value of the environment variable. If the environment /// variable is not present, then this will expand to `None`. /// /// A compile time error is never emitted when using this macro regardless /// of whether the environment variable is present or not. /// /// # Examples /// /// ``` /// let key: Option<&'static str> = option_env!("SECRET_KEY"); /// println!("the secret key might be: {:?}", key); /// ``` #[macro_export] macro_rules! option_env { ($name:expr) => ({ /* compiler built-in */ }) } /// Concatenate identifiers into one identifier. /// /// This macro takes any number of comma-separated identifiers, and /// concatenates them all into one, yielding an expression which is a new /// identifier. Note that hygiene makes it such that this macro cannot /// capture local variables, and macros are only allowed in item, /// statement or expression position, meaning this macro may be difficult to /// use in some situations. /// /// # Examples /// /// ``` /// #![feature(concat_idents)] /// /// # fn main() { /// fn foobar() -> u32 { 23 } /// /// let f = concat_idents!(foo, bar); /// println!("{}", f()); /// # } /// ``` #[macro_export] macro_rules! concat_idents { ($($e:ident),*) => ({ /* compiler built-in */ }) } /// Concatenates literals into a static string slice. /// /// This macro takes any number of comma-separated literals, yielding an /// expression of type `&'static str` which represents all of the literals /// concatenated left-to-right. /// /// Integer and floating point literals are stringified in order to be /// concatenated. /// /// # Examples /// /// ``` /// let s = concat!("test", 10, 'b', true); /// assert_eq!(s, "test10btrue"); /// ``` #[macro_export] macro_rules! concat { ($($e:expr),*) => ({ /* compiler built-in */ }) } /// A macro which expands to the line number on which it was invoked. /// /// The expanded expression has type `u32`, and the returned line is not /// the invocation of the `line!()` macro itself, but rather the first macro /// invocation leading up to the invocation of the `line!()` macro. /// /// # Examples /// /// ``` /// let current_line = line!(); /// println!("defined on line: {}", current_line); /// ``` #[macro_export] macro_rules! line { () => ({ /* compiler built-in */ }) } /// A macro which expands to the column number on which it was invoked. /// /// The expanded expression has type `u32`, and the returned column is not /// the invocation of the `column!()` macro itself, but rather the first macro /// invocation leading up to the invocation of the `column!()` macro. /// /// # Examples /// /// ``` /// let current_col = column!(); /// println!("defined on column: {}", current_col); /// ``` #[macro_export] macro_rules! column { () => ({ /* compiler built-in */ }) } /// A macro which expands to the file name from which it was invoked. /// /// The expanded expression has type `&'static str`, and the returned file /// is not the invocation of the `file!()` macro itself, but rather the /// first macro invocation leading up to the invocation of the `file!()` /// macro. /// /// # Examples /// /// ``` /// let this_file = file!(); /// println!("defined in file: {}", this_file); /// ``` #[macro_export] macro_rules! file { () => ({ /* compiler built-in */ }) } /// A macro which stringifies its argument. /// /// This macro will yield an expression of type `&'static str` which is the /// stringification of all the tokens passed to the macro. No restrictions /// are placed on the syntax of the macro invocation itself. /// /// # Examples /// /// ``` /// let one_plus_one = stringify!(1 + 1); /// assert_eq!(one_plus_one, "1 + 1"); /// ``` #[macro_export] macro_rules! stringify { ($t:tt) => ({ /* compiler built-in */ }) } /// Includes a utf8-encoded file as a string. /// /// This macro will yield an expression of type `&'static str` which is the /// contents of the filename specified. The file is located relative to the /// current file (similarly to how modules are found), /// /// # Examples /// /// ```rust,ignore /// let secret_key = include_str!("secret-key.ascii"); /// ``` #[macro_export] macro_rules! include_str { ($file:expr) => ({ /* compiler built-in */ }) } /// Includes a file as a reference to a byte array. /// /// This macro will yield an expression of type `&'static [u8; N]` which is /// the contents of the filename specified. The file is located relative to /// the current file (similarly to how modules are found), /// /// # Examples /// /// ```rust,ignore /// let secret_key = include_bytes!("secret-key.bin"); /// ``` #[macro_export] macro_rules! include_bytes { ($file:expr) => ({ /* compiler built-in */ }) } /// Expands to a string that represents the current module path. /// /// The current module path can be thought of as the hierarchy of modules /// leading back up to the crate root. The first component of the path /// returned is the name of the crate currently being compiled. /// /// # Examples /// /// ``` /// mod test { /// pub fn foo() { /// assert!(module_path!().ends_with("test")); /// } /// } /// /// test::foo(); /// ``` #[macro_export] macro_rules! module_path { () => ({ /* compiler built-in */ }) } /// Boolean evaluation of configuration flags. /// /// In addition to the `#[cfg]` attribute, this macro is provided to allow /// boolean expression evaluation of configuration flags. This frequently /// leads to less duplicated code. /// /// The syntax given to this macro is the same syntax as the `cfg` /// attribute. /// /// # Examples /// /// ``` /// let my_directory = if cfg!(windows) { /// "windows-specific-directory" /// } else { /// "unix-directory" /// }; /// ``` #[macro_export] macro_rules! cfg { ($cfg:tt) => ({ /* compiler built-in */ }) } /// Parse the current given file as an expression. /// /// This is generally a bad idea, because it's going to behave unhygienically. /// /// # Examples /// /// ```ignore /// fn foo() { /// include!("/path/to/a/file") /// } /// ``` #[macro_export] macro_rules! include { ($cfg:tt) => ({ /* compiler built-in */ }) } }
random_line_split
Login.tsx
import React from 'react' import { makeStyles, Button, TextField, FormControlLabel, Checkbox, Link, Grid, } from '@material-ui/core' import { Link as RouterLink } from 'react-router-dom' import AuthHeader from '../_common/AuthHeader' import AuthContent from '../_common/AuthContent' const Login: React.FC = () => { const classes = useStyles() return ( <AuthContent> <AuthHeader title={'Sign In'} /> <form className={classes.form} noValidate> <TextField variant="outlined" margin="normal" required fullWidth id="email" label="Email Address" name="email" autoComplete="email" autoFocus /> <TextField variant="outlined" margin="normal" required fullWidth name="password" label="Password" type="password" id="password" autoComplete="current-password" /> <FormControlLabel control={<Checkbox value="remember" color="primary" />} label="Remember me" /> <Button
color="primary" className={classes.submit} > Sign In </Button> <Grid container> <Grid item xs> <Link component={RouterLink} to="/auth/recover" variant="body2"> Forgot password? </Link> </Grid> <Grid item> <Link component={RouterLink} to="/auth/signup" variant="body2"> {"Don't have an account? Sign Up"} </Link> </Grid> </Grid> </form> </AuthContent> ) } const useStyles = makeStyles((theme) => ({ form: { width: '100%', // Fix IE 11 issue. marginTop: theme.spacing(1), }, submit: { margin: theme.spacing(3, 0, 2), }, })) export default Login
type="submit" fullWidth variant="contained"
random_line_split
bing.py
''' Created on Jan 2, 2015 @author: alessandro ''' import add_path import os import cv2 import sys import json import getopt import random import numpy as np from filter_tig import FilterTIG EDGE = 8 BASE_LOG = 2 MIN_EDGE_LOG = int(np.ceil(np.log(10.)/np.log(BASE_LOG))) MAX_EDGE_LOG = int(np.ceil(np.log(500.)/np.log(BASE_LOG))) EDGE_LOG_RANGE = MAX_EDGE_LOG - MIN_EDGE_LOG + 1 NUM_WIN_PSZ = 130 def magnitude(x,y): #return np.sqrt(np.square(x)+np.square(y)) return x + y def sobel_gradient(img, ksize): gray = cv2.cvtColor(img, cv2.cv.CV_BGR2GRAY) x = cv2.Sobel(gray,cv2.CV_64F,1,0,ksize=ksize) y = cv2.Sobel(gray,cv2.CV_64F,0,1,ksize=ksize) mag = magnitude(x,y) return mag def sobel_gradient_8u(img, ksize): grad = sobel_gradient(img, ksize) grad[grad<0] = 0 grad[grad>255] = 255 return grad.astype(np.uint8) def rgb_gradient(img): img = img.astype(float) h,w, nch = img.shape gradientX = np.zeros((h,w)) gradientY = np.zeros((h,w)) d1 = np.abs(img[:,1,:] - img[:,0,:]) gradientX[:,0] = np.max( d1, axis = 1) * 2 d2 = np.abs(img[:,-1,:] - img[:,-2,:]) gradientX[:,-1] = np.max( d2 , axis = 1) * 2 d3 = np.abs(img[:,2:w,:] - img[:,0:w-2,:]) gradientX[:,1:w-1] = np.max( d3 , axis = 2 ) d1 = np.abs(img[1,:,:] - img[0,:,:]) gradientY[0,:] = np.max( d1, axis = 1) * 2 d2 = np.abs(img[-1,:,:] - img[-2,:,:]) gradientY[-1,:] = np.max( d2 , axis = 1) * 2 d3 = np.abs(img[2:h,:,:] - img[0:h-2,:,:]) gradientY[1:h-1,:] = np.max( d3 , axis = 2 ) mag = magnitude(gradientX,gradientY) mag[mag<0] = 0 mag[mag>255] = 255 return mag.astype(np.uint8) def get_features(img,bb, w = EDGE,h = EDGE, ksize=3, idx = None): crop_img = img[bb[1]-1:bb[3], bb[0]-1:bb[2],:] if not idx is None: cv2.imwrite("/tmp/%s.png"%idx,crop_img) sub_img = cv2.resize(crop_img,(w,h)) grad = rgb_gradient(sub_img) return grad class FirstStagePrediction(object): def __init__(self, weights_1st_stage, scale_space_sizes_idxs, num_win_psz = 130, edge = EDGE, base_log = BASE_LOG, min_edge_log = MIN_EDGE_LOG, edge_log_range = EDGE_LOG_RANGE): self.filter_tig = FilterTIG() self.weights_1st_stage = weights_1st_stage self.filter_tig.update(self.weights_1st_stage) self.filter_tig.reconstruct(self.weights_1st_stage) self.scale_space_sizes_idxs = scale_space_sizes_idxs self.base_log = base_log self.min_edge_log = min_edge_log self.edge_log_range = edge_log_range self.edge = edge self.num_win_psz = num_win_psz def predict(self, image, nss = 2): bbs = [] img_h,img_w,nch = image.shape for size_idx in self.scale_space_sizes_idxs: w = round(pow(self.base_log, size_idx % self.edge_log_range + self.min_edge_log)) h = round(pow(self.base_log, size_idx // self.edge_log_range + self.min_edge_log)) if (h > img_h * self.base_log) or (w > img_w * self.base_log): continue h = min(h, img_h) w = min(w, img_w) new_w = int(round(float(self.edge)*img_w/w)) new_h = int(round(float(self.edge)*img_h/h)) img_resized = cv2.resize(image,(new_w,new_h)) grad = rgb_gradient(img_resized) match_map = self.filter_tig.match_template(grad) points = self.filter_tig.non_maxima_suppression(match_map, nss, self.num_win_psz, False) ratio_x = w / self.edge ratio_y = h / self.edge i_max = min(len(points), self.num_win_psz) for i in xrange(i_max): point, score = points[i] x0 = int(round(point[0] * ratio_x)) y0 = int(round(point[1] * ratio_y)) x1 = min(img_w, int(x0+w)) y1 = min(img_h, int(y0+h)) x0 = x0 + 1 y0 = y0 + 1 bbs.append(((x0,y0,x1,y1), score, size_idx)) return bbs class SecondStagePrediction(object): def __init__(self, second_stage_weights): self.second_stage_weights = second_stage_weights def predict(self, bbs): normalized_bbs = [] for bb, score, size_idx in bbs: try: weights = self.second_stage_weights["%s"%size_idx] except: #if a size_idx is missing, it means that training error for it was empty, so just skip it! continue #normalize the score with respect with the size normalized_score = weights["weight"] * score + weights["bias"] normalized_bbs.append((normalized_score,bb)) return normalized_bbs class Bing(object): def __init__(self, weights_1st_stage, sizes_idx, weights_2nd_stage, num_bbs_per_size_1st_stage= NUM_WIN_PSZ, num_bbs_final = 1500, edge = EDGE, base_log = BASE_LOG, min_edge_log = MIN_EDGE_LOG, edge_log_range = EDGE_LOG_RANGE): self.first_stage_prediction = FirstStagePrediction(weights_1st_stage, sizes_idx, num_win_psz = num_bbs_per_size_1st_stage, edge = edge, base_log = base_log, min_edge_log = min_edge_log, edge_log_range = edge_log_range) self.second_stage_prediction = SecondStagePrediction(weights_2nd_stage) self.num_bbs_final = num_bbs_final def predict(self, image): bbs_1st = self.first_stage_prediction.predict(image) bbs = self.second_stage_prediction.predict(bbs_1st) sorted_bbs = sorted(bbs, key = lambda x:x[0], reverse = True) results = [(bb[0],bb[1]) for bb in sorted_bbs[:self.num_bbs_final]] score_bbs, results_bbs = zip(*results) return results_bbs, score_bbs def parse_cmdline_inputs(): """ Example parameters: { "basepath": "/opt/Datasets/VOC2007", "training_set_fn": "/opt/Datasets/VOC2007/ImageSets/Main/train.txt", "test_set_fn": "/opt/Datasets/VOC2007/ImageSets/Main/test.txt", "annotations_path": "/opt/Datasets/VOC2007/Annotations", "images_path": "/opt/Datasets/VOC2007/JPEGImages", "results_dir": "/opt/Datasets/VOC2007/BING_Results", "1st_stage_weights_fn":"/opt/Datasets/VOC2007/BING_Results/weights.txt", "2nd_stage_weights_fn": "/opt/Datasets/VOC2007/BING_Results/2nd_stage_weights.json", "sizes_indeces_fn": "/opt/Datasets/VOC2007/BING_Results/sizes.txt", "num_win_psz": 130, "num_bbs": 1500 } """ try: opts, args = getopt.getopt(sys.argv[1:], "h", ["help", "num_bbs_per_size=", "num_bbs=" ]) except getopt.GetoptError as err: # print help information and exit: print str(err) # will print something like "option -a not recognized" sys.exit(2) params_file = sys.argv[-2] if not os.path.exists(params_file): print "Specified file for parameters %s does not exist."%params_file sys.exit(2) try: f = open(params_file, "r") params_str = f.read() f.close() except Exception as e: print "Error while reading parameters file %s. Exception: %s."%(params_file,e) sys.exit(2) try: params = json.loads(params_str) except Exception as e: print "Error while parsing parameters json file %s. Exception: %s."%(params_file,e) sys.exit(2) for o, a in opts: if o == "--help" or o =="-h":
elif o == "--num_bbs_per_size": try: params["num_win_psz"] = int(a) except Exception as e: print "Error while converting parameter --num_bb_per_size %s to int. Exception: %s."%(a,e) sys.exit(2) elif o == "--num_bbs": try: params["num_bbs"] = int(a) except Exception as e: print "Error while converting parameter --num_bbs %s to int. Exception: %s."%(a,e) sys.exit(2) else: print "Invalid parameter %s. Type 'python bing -h' "%o sys.exit(2) if not params.has_key("num_bbs"): params["num_bbs"] = 1500 if not params.has_key("num_win_psz"): params["num_win_psz"] = 130 params["image_file"] = sys.argv[-1] if not os.path.exists(params["image_file"]): print "Specified file for image %s does not exist."%params["image_file"] sys.exit(2) image = cv2.imread(params["image_file"]) return params, image if __name__=="__main__": params, image = parse_cmdline_inputs() results_dir = params["results_dir"] if not os.path.exists(results_dir): print "The results directory that should contains weights and sizes indeces does not exist. Be sure to have already performed training. " sys.exit(2) if not os.path.exists(params["1st_stage_weights_fn"]): print "The weights for the first stage does not exist!" sys.exit(2) w_1st = np.genfromtxt(params["1st_stage_weights_fn"], delimiter=",").astype(np.float32) if not os.path.exists(params["sizes_indeces_fn"]): print "The sizes indices file does not exist!" sys.exit(2) sizes = np.genfromtxt(params["sizes_indeces_fn"], delimiter=",").astype(np.int32) if not os.path.exists(params["2nd_stage_weights_fn"]): print "The weights for the second stage does not exist!" sys.exit(2) f = open(params["2nd_stage_weights_fn"]) w_str = f.read() f.close() w_2nd = json.loads(w_str) b = Bing(w_1st,sizes,w_2nd, num_bbs_per_size_1st_stage= params["num_win_psz"], num_bbs_final = params["num_bbs"]) bbs, scores = b.predict(image) for bb in bbs: cv2.rectangle(image,(bb[0],bb[1]),(bb[2],bb[3]),color=(random.randint(0,255),random.randint(0,255),random.randint(0,255))) cv2.imwrite(os.path.join(results_dir, "bounding_box_image.png"), image) f = open(os.path.join(results_dir,"bbs.csv"),"w") f.write("filename,xmin,ymin,xmax,ymax\n") for bb in bbs: f.write("%s,%s,%s,%s,%s\n"%(params["image_file"],bb[0],bb[1],bb[2],bb[3])) f.close()
print "python bing.py --num_bbs_per_size 130 --num_bbs 1500 /path/to/dataset/parameters.json /path/to/image.jpg" sys.exit(0)
conditional_block
bing.py
''' Created on Jan 2, 2015 @author: alessandro ''' import add_path import os import cv2 import sys import json import getopt import random import numpy as np from filter_tig import FilterTIG EDGE = 8 BASE_LOG = 2 MIN_EDGE_LOG = int(np.ceil(np.log(10.)/np.log(BASE_LOG))) MAX_EDGE_LOG = int(np.ceil(np.log(500.)/np.log(BASE_LOG))) EDGE_LOG_RANGE = MAX_EDGE_LOG - MIN_EDGE_LOG + 1 NUM_WIN_PSZ = 130 def magnitude(x,y): #return np.sqrt(np.square(x)+np.square(y)) return x + y def sobel_gradient(img, ksize): gray = cv2.cvtColor(img, cv2.cv.CV_BGR2GRAY) x = cv2.Sobel(gray,cv2.CV_64F,1,0,ksize=ksize) y = cv2.Sobel(gray,cv2.CV_64F,0,1,ksize=ksize) mag = magnitude(x,y) return mag def sobel_gradient_8u(img, ksize): grad = sobel_gradient(img, ksize) grad[grad<0] = 0 grad[grad>255] = 255 return grad.astype(np.uint8) def rgb_gradient(img): img = img.astype(float) h,w, nch = img.shape gradientX = np.zeros((h,w)) gradientY = np.zeros((h,w)) d1 = np.abs(img[:,1,:] - img[:,0,:]) gradientX[:,0] = np.max( d1, axis = 1) * 2 d2 = np.abs(img[:,-1,:] - img[:,-2,:]) gradientX[:,-1] = np.max( d2 , axis = 1) * 2 d3 = np.abs(img[:,2:w,:] - img[:,0:w-2,:]) gradientX[:,1:w-1] = np.max( d3 , axis = 2 ) d1 = np.abs(img[1,:,:] - img[0,:,:]) gradientY[0,:] = np.max( d1, axis = 1) * 2 d2 = np.abs(img[-1,:,:] - img[-2,:,:]) gradientY[-1,:] = np.max( d2 , axis = 1) * 2 d3 = np.abs(img[2:h,:,:] - img[0:h-2,:,:]) gradientY[1:h-1,:] = np.max( d3 , axis = 2 ) mag = magnitude(gradientX,gradientY) mag[mag<0] = 0 mag[mag>255] = 255 return mag.astype(np.uint8) def get_features(img,bb, w = EDGE,h = EDGE, ksize=3, idx = None): crop_img = img[bb[1]-1:bb[3], bb[0]-1:bb[2],:] if not idx is None: cv2.imwrite("/tmp/%s.png"%idx,crop_img) sub_img = cv2.resize(crop_img,(w,h)) grad = rgb_gradient(sub_img) return grad class FirstStagePrediction(object):
class SecondStagePrediction(object): def __init__(self, second_stage_weights): self.second_stage_weights = second_stage_weights def predict(self, bbs): normalized_bbs = [] for bb, score, size_idx in bbs: try: weights = self.second_stage_weights["%s"%size_idx] except: #if a size_idx is missing, it means that training error for it was empty, so just skip it! continue #normalize the score with respect with the size normalized_score = weights["weight"] * score + weights["bias"] normalized_bbs.append((normalized_score,bb)) return normalized_bbs class Bing(object): def __init__(self, weights_1st_stage, sizes_idx, weights_2nd_stage, num_bbs_per_size_1st_stage= NUM_WIN_PSZ, num_bbs_final = 1500, edge = EDGE, base_log = BASE_LOG, min_edge_log = MIN_EDGE_LOG, edge_log_range = EDGE_LOG_RANGE): self.first_stage_prediction = FirstStagePrediction(weights_1st_stage, sizes_idx, num_win_psz = num_bbs_per_size_1st_stage, edge = edge, base_log = base_log, min_edge_log = min_edge_log, edge_log_range = edge_log_range) self.second_stage_prediction = SecondStagePrediction(weights_2nd_stage) self.num_bbs_final = num_bbs_final def predict(self, image): bbs_1st = self.first_stage_prediction.predict(image) bbs = self.second_stage_prediction.predict(bbs_1st) sorted_bbs = sorted(bbs, key = lambda x:x[0], reverse = True) results = [(bb[0],bb[1]) for bb in sorted_bbs[:self.num_bbs_final]] score_bbs, results_bbs = zip(*results) return results_bbs, score_bbs def parse_cmdline_inputs(): """ Example parameters: { "basepath": "/opt/Datasets/VOC2007", "training_set_fn": "/opt/Datasets/VOC2007/ImageSets/Main/train.txt", "test_set_fn": "/opt/Datasets/VOC2007/ImageSets/Main/test.txt", "annotations_path": "/opt/Datasets/VOC2007/Annotations", "images_path": "/opt/Datasets/VOC2007/JPEGImages", "results_dir": "/opt/Datasets/VOC2007/BING_Results", "1st_stage_weights_fn":"/opt/Datasets/VOC2007/BING_Results/weights.txt", "2nd_stage_weights_fn": "/opt/Datasets/VOC2007/BING_Results/2nd_stage_weights.json", "sizes_indeces_fn": "/opt/Datasets/VOC2007/BING_Results/sizes.txt", "num_win_psz": 130, "num_bbs": 1500 } """ try: opts, args = getopt.getopt(sys.argv[1:], "h", ["help", "num_bbs_per_size=", "num_bbs=" ]) except getopt.GetoptError as err: # print help information and exit: print str(err) # will print something like "option -a not recognized" sys.exit(2) params_file = sys.argv[-2] if not os.path.exists(params_file): print "Specified file for parameters %s does not exist."%params_file sys.exit(2) try: f = open(params_file, "r") params_str = f.read() f.close() except Exception as e: print "Error while reading parameters file %s. Exception: %s."%(params_file,e) sys.exit(2) try: params = json.loads(params_str) except Exception as e: print "Error while parsing parameters json file %s. Exception: %s."%(params_file,e) sys.exit(2) for o, a in opts: if o == "--help" or o =="-h": print "python bing.py --num_bbs_per_size 130 --num_bbs 1500 /path/to/dataset/parameters.json /path/to/image.jpg" sys.exit(0) elif o == "--num_bbs_per_size": try: params["num_win_psz"] = int(a) except Exception as e: print "Error while converting parameter --num_bb_per_size %s to int. Exception: %s."%(a,e) sys.exit(2) elif o == "--num_bbs": try: params["num_bbs"] = int(a) except Exception as e: print "Error while converting parameter --num_bbs %s to int. Exception: %s."%(a,e) sys.exit(2) else: print "Invalid parameter %s. Type 'python bing -h' "%o sys.exit(2) if not params.has_key("num_bbs"): params["num_bbs"] = 1500 if not params.has_key("num_win_psz"): params["num_win_psz"] = 130 params["image_file"] = sys.argv[-1] if not os.path.exists(params["image_file"]): print "Specified file for image %s does not exist."%params["image_file"] sys.exit(2) image = cv2.imread(params["image_file"]) return params, image if __name__=="__main__": params, image = parse_cmdline_inputs() results_dir = params["results_dir"] if not os.path.exists(results_dir): print "The results directory that should contains weights and sizes indeces does not exist. Be sure to have already performed training. " sys.exit(2) if not os.path.exists(params["1st_stage_weights_fn"]): print "The weights for the first stage does not exist!" sys.exit(2) w_1st = np.genfromtxt(params["1st_stage_weights_fn"], delimiter=",").astype(np.float32) if not os.path.exists(params["sizes_indeces_fn"]): print "The sizes indices file does not exist!" sys.exit(2) sizes = np.genfromtxt(params["sizes_indeces_fn"], delimiter=",").astype(np.int32) if not os.path.exists(params["2nd_stage_weights_fn"]): print "The weights for the second stage does not exist!" sys.exit(2) f = open(params["2nd_stage_weights_fn"]) w_str = f.read() f.close() w_2nd = json.loads(w_str) b = Bing(w_1st,sizes,w_2nd, num_bbs_per_size_1st_stage= params["num_win_psz"], num_bbs_final = params["num_bbs"]) bbs, scores = b.predict(image) for bb in bbs: cv2.rectangle(image,(bb[0],bb[1]),(bb[2],bb[3]),color=(random.randint(0,255),random.randint(0,255),random.randint(0,255))) cv2.imwrite(os.path.join(results_dir, "bounding_box_image.png"), image) f = open(os.path.join(results_dir,"bbs.csv"),"w") f.write("filename,xmin,ymin,xmax,ymax\n") for bb in bbs: f.write("%s,%s,%s,%s,%s\n"%(params["image_file"],bb[0],bb[1],bb[2],bb[3])) f.close()
def __init__(self, weights_1st_stage, scale_space_sizes_idxs, num_win_psz = 130, edge = EDGE, base_log = BASE_LOG, min_edge_log = MIN_EDGE_LOG, edge_log_range = EDGE_LOG_RANGE): self.filter_tig = FilterTIG() self.weights_1st_stage = weights_1st_stage self.filter_tig.update(self.weights_1st_stage) self.filter_tig.reconstruct(self.weights_1st_stage) self.scale_space_sizes_idxs = scale_space_sizes_idxs self.base_log = base_log self.min_edge_log = min_edge_log self.edge_log_range = edge_log_range self.edge = edge self.num_win_psz = num_win_psz def predict(self, image, nss = 2): bbs = [] img_h,img_w,nch = image.shape for size_idx in self.scale_space_sizes_idxs: w = round(pow(self.base_log, size_idx % self.edge_log_range + self.min_edge_log)) h = round(pow(self.base_log, size_idx // self.edge_log_range + self.min_edge_log)) if (h > img_h * self.base_log) or (w > img_w * self.base_log): continue h = min(h, img_h) w = min(w, img_w) new_w = int(round(float(self.edge)*img_w/w)) new_h = int(round(float(self.edge)*img_h/h)) img_resized = cv2.resize(image,(new_w,new_h)) grad = rgb_gradient(img_resized) match_map = self.filter_tig.match_template(grad) points = self.filter_tig.non_maxima_suppression(match_map, nss, self.num_win_psz, False) ratio_x = w / self.edge ratio_y = h / self.edge i_max = min(len(points), self.num_win_psz) for i in xrange(i_max): point, score = points[i] x0 = int(round(point[0] * ratio_x)) y0 = int(round(point[1] * ratio_y)) x1 = min(img_w, int(x0+w)) y1 = min(img_h, int(y0+h)) x0 = x0 + 1 y0 = y0 + 1 bbs.append(((x0,y0,x1,y1), score, size_idx)) return bbs
identifier_body
bing.py
''' Created on Jan 2, 2015 @author: alessandro ''' import add_path import os import cv2 import sys import json import getopt import random import numpy as np from filter_tig import FilterTIG EDGE = 8 BASE_LOG = 2 MIN_EDGE_LOG = int(np.ceil(np.log(10.)/np.log(BASE_LOG))) MAX_EDGE_LOG = int(np.ceil(np.log(500.)/np.log(BASE_LOG))) EDGE_LOG_RANGE = MAX_EDGE_LOG - MIN_EDGE_LOG + 1 NUM_WIN_PSZ = 130 def magnitude(x,y): #return np.sqrt(np.square(x)+np.square(y)) return x + y def
(img, ksize): gray = cv2.cvtColor(img, cv2.cv.CV_BGR2GRAY) x = cv2.Sobel(gray,cv2.CV_64F,1,0,ksize=ksize) y = cv2.Sobel(gray,cv2.CV_64F,0,1,ksize=ksize) mag = magnitude(x,y) return mag def sobel_gradient_8u(img, ksize): grad = sobel_gradient(img, ksize) grad[grad<0] = 0 grad[grad>255] = 255 return grad.astype(np.uint8) def rgb_gradient(img): img = img.astype(float) h,w, nch = img.shape gradientX = np.zeros((h,w)) gradientY = np.zeros((h,w)) d1 = np.abs(img[:,1,:] - img[:,0,:]) gradientX[:,0] = np.max( d1, axis = 1) * 2 d2 = np.abs(img[:,-1,:] - img[:,-2,:]) gradientX[:,-1] = np.max( d2 , axis = 1) * 2 d3 = np.abs(img[:,2:w,:] - img[:,0:w-2,:]) gradientX[:,1:w-1] = np.max( d3 , axis = 2 ) d1 = np.abs(img[1,:,:] - img[0,:,:]) gradientY[0,:] = np.max( d1, axis = 1) * 2 d2 = np.abs(img[-1,:,:] - img[-2,:,:]) gradientY[-1,:] = np.max( d2 , axis = 1) * 2 d3 = np.abs(img[2:h,:,:] - img[0:h-2,:,:]) gradientY[1:h-1,:] = np.max( d3 , axis = 2 ) mag = magnitude(gradientX,gradientY) mag[mag<0] = 0 mag[mag>255] = 255 return mag.astype(np.uint8) def get_features(img,bb, w = EDGE,h = EDGE, ksize=3, idx = None): crop_img = img[bb[1]-1:bb[3], bb[0]-1:bb[2],:] if not idx is None: cv2.imwrite("/tmp/%s.png"%idx,crop_img) sub_img = cv2.resize(crop_img,(w,h)) grad = rgb_gradient(sub_img) return grad class FirstStagePrediction(object): def __init__(self, weights_1st_stage, scale_space_sizes_idxs, num_win_psz = 130, edge = EDGE, base_log = BASE_LOG, min_edge_log = MIN_EDGE_LOG, edge_log_range = EDGE_LOG_RANGE): self.filter_tig = FilterTIG() self.weights_1st_stage = weights_1st_stage self.filter_tig.update(self.weights_1st_stage) self.filter_tig.reconstruct(self.weights_1st_stage) self.scale_space_sizes_idxs = scale_space_sizes_idxs self.base_log = base_log self.min_edge_log = min_edge_log self.edge_log_range = edge_log_range self.edge = edge self.num_win_psz = num_win_psz def predict(self, image, nss = 2): bbs = [] img_h,img_w,nch = image.shape for size_idx in self.scale_space_sizes_idxs: w = round(pow(self.base_log, size_idx % self.edge_log_range + self.min_edge_log)) h = round(pow(self.base_log, size_idx // self.edge_log_range + self.min_edge_log)) if (h > img_h * self.base_log) or (w > img_w * self.base_log): continue h = min(h, img_h) w = min(w, img_w) new_w = int(round(float(self.edge)*img_w/w)) new_h = int(round(float(self.edge)*img_h/h)) img_resized = cv2.resize(image,(new_w,new_h)) grad = rgb_gradient(img_resized) match_map = self.filter_tig.match_template(grad) points = self.filter_tig.non_maxima_suppression(match_map, nss, self.num_win_psz, False) ratio_x = w / self.edge ratio_y = h / self.edge i_max = min(len(points), self.num_win_psz) for i in xrange(i_max): point, score = points[i] x0 = int(round(point[0] * ratio_x)) y0 = int(round(point[1] * ratio_y)) x1 = min(img_w, int(x0+w)) y1 = min(img_h, int(y0+h)) x0 = x0 + 1 y0 = y0 + 1 bbs.append(((x0,y0,x1,y1), score, size_idx)) return bbs class SecondStagePrediction(object): def __init__(self, second_stage_weights): self.second_stage_weights = second_stage_weights def predict(self, bbs): normalized_bbs = [] for bb, score, size_idx in bbs: try: weights = self.second_stage_weights["%s"%size_idx] except: #if a size_idx is missing, it means that training error for it was empty, so just skip it! continue #normalize the score with respect with the size normalized_score = weights["weight"] * score + weights["bias"] normalized_bbs.append((normalized_score,bb)) return normalized_bbs class Bing(object): def __init__(self, weights_1st_stage, sizes_idx, weights_2nd_stage, num_bbs_per_size_1st_stage= NUM_WIN_PSZ, num_bbs_final = 1500, edge = EDGE, base_log = BASE_LOG, min_edge_log = MIN_EDGE_LOG, edge_log_range = EDGE_LOG_RANGE): self.first_stage_prediction = FirstStagePrediction(weights_1st_stage, sizes_idx, num_win_psz = num_bbs_per_size_1st_stage, edge = edge, base_log = base_log, min_edge_log = min_edge_log, edge_log_range = edge_log_range) self.second_stage_prediction = SecondStagePrediction(weights_2nd_stage) self.num_bbs_final = num_bbs_final def predict(self, image): bbs_1st = self.first_stage_prediction.predict(image) bbs = self.second_stage_prediction.predict(bbs_1st) sorted_bbs = sorted(bbs, key = lambda x:x[0], reverse = True) results = [(bb[0],bb[1]) for bb in sorted_bbs[:self.num_bbs_final]] score_bbs, results_bbs = zip(*results) return results_bbs, score_bbs def parse_cmdline_inputs(): """ Example parameters: { "basepath": "/opt/Datasets/VOC2007", "training_set_fn": "/opt/Datasets/VOC2007/ImageSets/Main/train.txt", "test_set_fn": "/opt/Datasets/VOC2007/ImageSets/Main/test.txt", "annotations_path": "/opt/Datasets/VOC2007/Annotations", "images_path": "/opt/Datasets/VOC2007/JPEGImages", "results_dir": "/opt/Datasets/VOC2007/BING_Results", "1st_stage_weights_fn":"/opt/Datasets/VOC2007/BING_Results/weights.txt", "2nd_stage_weights_fn": "/opt/Datasets/VOC2007/BING_Results/2nd_stage_weights.json", "sizes_indeces_fn": "/opt/Datasets/VOC2007/BING_Results/sizes.txt", "num_win_psz": 130, "num_bbs": 1500 } """ try: opts, args = getopt.getopt(sys.argv[1:], "h", ["help", "num_bbs_per_size=", "num_bbs=" ]) except getopt.GetoptError as err: # print help information and exit: print str(err) # will print something like "option -a not recognized" sys.exit(2) params_file = sys.argv[-2] if not os.path.exists(params_file): print "Specified file for parameters %s does not exist."%params_file sys.exit(2) try: f = open(params_file, "r") params_str = f.read() f.close() except Exception as e: print "Error while reading parameters file %s. Exception: %s."%(params_file,e) sys.exit(2) try: params = json.loads(params_str) except Exception as e: print "Error while parsing parameters json file %s. Exception: %s."%(params_file,e) sys.exit(2) for o, a in opts: if o == "--help" or o =="-h": print "python bing.py --num_bbs_per_size 130 --num_bbs 1500 /path/to/dataset/parameters.json /path/to/image.jpg" sys.exit(0) elif o == "--num_bbs_per_size": try: params["num_win_psz"] = int(a) except Exception as e: print "Error while converting parameter --num_bb_per_size %s to int. Exception: %s."%(a,e) sys.exit(2) elif o == "--num_bbs": try: params["num_bbs"] = int(a) except Exception as e: print "Error while converting parameter --num_bbs %s to int. Exception: %s."%(a,e) sys.exit(2) else: print "Invalid parameter %s. Type 'python bing -h' "%o sys.exit(2) if not params.has_key("num_bbs"): params["num_bbs"] = 1500 if not params.has_key("num_win_psz"): params["num_win_psz"] = 130 params["image_file"] = sys.argv[-1] if not os.path.exists(params["image_file"]): print "Specified file for image %s does not exist."%params["image_file"] sys.exit(2) image = cv2.imread(params["image_file"]) return params, image if __name__=="__main__": params, image = parse_cmdline_inputs() results_dir = params["results_dir"] if not os.path.exists(results_dir): print "The results directory that should contains weights and sizes indeces does not exist. Be sure to have already performed training. " sys.exit(2) if not os.path.exists(params["1st_stage_weights_fn"]): print "The weights for the first stage does not exist!" sys.exit(2) w_1st = np.genfromtxt(params["1st_stage_weights_fn"], delimiter=",").astype(np.float32) if not os.path.exists(params["sizes_indeces_fn"]): print "The sizes indices file does not exist!" sys.exit(2) sizes = np.genfromtxt(params["sizes_indeces_fn"], delimiter=",").astype(np.int32) if not os.path.exists(params["2nd_stage_weights_fn"]): print "The weights for the second stage does not exist!" sys.exit(2) f = open(params["2nd_stage_weights_fn"]) w_str = f.read() f.close() w_2nd = json.loads(w_str) b = Bing(w_1st,sizes,w_2nd, num_bbs_per_size_1st_stage= params["num_win_psz"], num_bbs_final = params["num_bbs"]) bbs, scores = b.predict(image) for bb in bbs: cv2.rectangle(image,(bb[0],bb[1]),(bb[2],bb[3]),color=(random.randint(0,255),random.randint(0,255),random.randint(0,255))) cv2.imwrite(os.path.join(results_dir, "bounding_box_image.png"), image) f = open(os.path.join(results_dir,"bbs.csv"),"w") f.write("filename,xmin,ymin,xmax,ymax\n") for bb in bbs: f.write("%s,%s,%s,%s,%s\n"%(params["image_file"],bb[0],bb[1],bb[2],bb[3])) f.close()
sobel_gradient
identifier_name
bing.py
''' Created on Jan 2, 2015 @author: alessandro ''' import add_path import os import cv2 import sys import json import getopt import random import numpy as np from filter_tig import FilterTIG EDGE = 8 BASE_LOG = 2 MIN_EDGE_LOG = int(np.ceil(np.log(10.)/np.log(BASE_LOG))) MAX_EDGE_LOG = int(np.ceil(np.log(500.)/np.log(BASE_LOG))) EDGE_LOG_RANGE = MAX_EDGE_LOG - MIN_EDGE_LOG + 1 NUM_WIN_PSZ = 130 def magnitude(x,y): #return np.sqrt(np.square(x)+np.square(y)) return x + y def sobel_gradient(img, ksize): gray = cv2.cvtColor(img, cv2.cv.CV_BGR2GRAY) x = cv2.Sobel(gray,cv2.CV_64F,1,0,ksize=ksize) y = cv2.Sobel(gray,cv2.CV_64F,0,1,ksize=ksize) mag = magnitude(x,y) return mag def sobel_gradient_8u(img, ksize): grad = sobel_gradient(img, ksize) grad[grad<0] = 0 grad[grad>255] = 255 return grad.astype(np.uint8) def rgb_gradient(img): img = img.astype(float) h,w, nch = img.shape gradientX = np.zeros((h,w)) gradientY = np.zeros((h,w)) d1 = np.abs(img[:,1,:] - img[:,0,:]) gradientX[:,0] = np.max( d1, axis = 1) * 2 d2 = np.abs(img[:,-1,:] - img[:,-2,:]) gradientX[:,-1] = np.max( d2 , axis = 1) * 2 d3 = np.abs(img[:,2:w,:] - img[:,0:w-2,:]) gradientX[:,1:w-1] = np.max( d3 , axis = 2 ) d1 = np.abs(img[1,:,:] - img[0,:,:]) gradientY[0,:] = np.max( d1, axis = 1) * 2 d2 = np.abs(img[-1,:,:] - img[-2,:,:]) gradientY[-1,:] = np.max( d2 , axis = 1) * 2 d3 = np.abs(img[2:h,:,:] - img[0:h-2,:,:]) gradientY[1:h-1,:] = np.max( d3 , axis = 2 ) mag = magnitude(gradientX,gradientY) mag[mag<0] = 0 mag[mag>255] = 255 return mag.astype(np.uint8) def get_features(img,bb, w = EDGE,h = EDGE, ksize=3, idx = None): crop_img = img[bb[1]-1:bb[3], bb[0]-1:bb[2],:] if not idx is None: cv2.imwrite("/tmp/%s.png"%idx,crop_img) sub_img = cv2.resize(crop_img,(w,h)) grad = rgb_gradient(sub_img) return grad class FirstStagePrediction(object): def __init__(self, weights_1st_stage, scale_space_sizes_idxs, num_win_psz = 130, edge = EDGE, base_log = BASE_LOG, min_edge_log = MIN_EDGE_LOG, edge_log_range = EDGE_LOG_RANGE): self.filter_tig = FilterTIG() self.weights_1st_stage = weights_1st_stage self.filter_tig.update(self.weights_1st_stage) self.filter_tig.reconstruct(self.weights_1st_stage) self.scale_space_sizes_idxs = scale_space_sizes_idxs self.base_log = base_log self.min_edge_log = min_edge_log self.edge_log_range = edge_log_range self.edge = edge self.num_win_psz = num_win_psz def predict(self, image, nss = 2): bbs = [] img_h,img_w,nch = image.shape for size_idx in self.scale_space_sizes_idxs: w = round(pow(self.base_log, size_idx % self.edge_log_range + self.min_edge_log))
new_w = int(round(float(self.edge)*img_w/w)) new_h = int(round(float(self.edge)*img_h/h)) img_resized = cv2.resize(image,(new_w,new_h)) grad = rgb_gradient(img_resized) match_map = self.filter_tig.match_template(grad) points = self.filter_tig.non_maxima_suppression(match_map, nss, self.num_win_psz, False) ratio_x = w / self.edge ratio_y = h / self.edge i_max = min(len(points), self.num_win_psz) for i in xrange(i_max): point, score = points[i] x0 = int(round(point[0] * ratio_x)) y0 = int(round(point[1] * ratio_y)) x1 = min(img_w, int(x0+w)) y1 = min(img_h, int(y0+h)) x0 = x0 + 1 y0 = y0 + 1 bbs.append(((x0,y0,x1,y1), score, size_idx)) return bbs class SecondStagePrediction(object): def __init__(self, second_stage_weights): self.second_stage_weights = second_stage_weights def predict(self, bbs): normalized_bbs = [] for bb, score, size_idx in bbs: try: weights = self.second_stage_weights["%s"%size_idx] except: #if a size_idx is missing, it means that training error for it was empty, so just skip it! continue #normalize the score with respect with the size normalized_score = weights["weight"] * score + weights["bias"] normalized_bbs.append((normalized_score,bb)) return normalized_bbs class Bing(object): def __init__(self, weights_1st_stage, sizes_idx, weights_2nd_stage, num_bbs_per_size_1st_stage= NUM_WIN_PSZ, num_bbs_final = 1500, edge = EDGE, base_log = BASE_LOG, min_edge_log = MIN_EDGE_LOG, edge_log_range = EDGE_LOG_RANGE): self.first_stage_prediction = FirstStagePrediction(weights_1st_stage, sizes_idx, num_win_psz = num_bbs_per_size_1st_stage, edge = edge, base_log = base_log, min_edge_log = min_edge_log, edge_log_range = edge_log_range) self.second_stage_prediction = SecondStagePrediction(weights_2nd_stage) self.num_bbs_final = num_bbs_final def predict(self, image): bbs_1st = self.first_stage_prediction.predict(image) bbs = self.second_stage_prediction.predict(bbs_1st) sorted_bbs = sorted(bbs, key = lambda x:x[0], reverse = True) results = [(bb[0],bb[1]) for bb in sorted_bbs[:self.num_bbs_final]] score_bbs, results_bbs = zip(*results) return results_bbs, score_bbs def parse_cmdline_inputs(): """ Example parameters: { "basepath": "/opt/Datasets/VOC2007", "training_set_fn": "/opt/Datasets/VOC2007/ImageSets/Main/train.txt", "test_set_fn": "/opt/Datasets/VOC2007/ImageSets/Main/test.txt", "annotations_path": "/opt/Datasets/VOC2007/Annotations", "images_path": "/opt/Datasets/VOC2007/JPEGImages", "results_dir": "/opt/Datasets/VOC2007/BING_Results", "1st_stage_weights_fn":"/opt/Datasets/VOC2007/BING_Results/weights.txt", "2nd_stage_weights_fn": "/opt/Datasets/VOC2007/BING_Results/2nd_stage_weights.json", "sizes_indeces_fn": "/opt/Datasets/VOC2007/BING_Results/sizes.txt", "num_win_psz": 130, "num_bbs": 1500 } """ try: opts, args = getopt.getopt(sys.argv[1:], "h", ["help", "num_bbs_per_size=", "num_bbs=" ]) except getopt.GetoptError as err: # print help information and exit: print str(err) # will print something like "option -a not recognized" sys.exit(2) params_file = sys.argv[-2] if not os.path.exists(params_file): print "Specified file for parameters %s does not exist."%params_file sys.exit(2) try: f = open(params_file, "r") params_str = f.read() f.close() except Exception as e: print "Error while reading parameters file %s. Exception: %s."%(params_file,e) sys.exit(2) try: params = json.loads(params_str) except Exception as e: print "Error while parsing parameters json file %s. Exception: %s."%(params_file,e) sys.exit(2) for o, a in opts: if o == "--help" or o =="-h": print "python bing.py --num_bbs_per_size 130 --num_bbs 1500 /path/to/dataset/parameters.json /path/to/image.jpg" sys.exit(0) elif o == "--num_bbs_per_size": try: params["num_win_psz"] = int(a) except Exception as e: print "Error while converting parameter --num_bb_per_size %s to int. Exception: %s."%(a,e) sys.exit(2) elif o == "--num_bbs": try: params["num_bbs"] = int(a) except Exception as e: print "Error while converting parameter --num_bbs %s to int. Exception: %s."%(a,e) sys.exit(2) else: print "Invalid parameter %s. Type 'python bing -h' "%o sys.exit(2) if not params.has_key("num_bbs"): params["num_bbs"] = 1500 if not params.has_key("num_win_psz"): params["num_win_psz"] = 130 params["image_file"] = sys.argv[-1] if not os.path.exists(params["image_file"]): print "Specified file for image %s does not exist."%params["image_file"] sys.exit(2) image = cv2.imread(params["image_file"]) return params, image if __name__=="__main__": params, image = parse_cmdline_inputs() results_dir = params["results_dir"] if not os.path.exists(results_dir): print "The results directory that should contains weights and sizes indeces does not exist. Be sure to have already performed training. " sys.exit(2) if not os.path.exists(params["1st_stage_weights_fn"]): print "The weights for the first stage does not exist!" sys.exit(2) w_1st = np.genfromtxt(params["1st_stage_weights_fn"], delimiter=",").astype(np.float32) if not os.path.exists(params["sizes_indeces_fn"]): print "The sizes indices file does not exist!" sys.exit(2) sizes = np.genfromtxt(params["sizes_indeces_fn"], delimiter=",").astype(np.int32) if not os.path.exists(params["2nd_stage_weights_fn"]): print "The weights for the second stage does not exist!" sys.exit(2) f = open(params["2nd_stage_weights_fn"]) w_str = f.read() f.close() w_2nd = json.loads(w_str) b = Bing(w_1st,sizes,w_2nd, num_bbs_per_size_1st_stage= params["num_win_psz"], num_bbs_final = params["num_bbs"]) bbs, scores = b.predict(image) for bb in bbs: cv2.rectangle(image,(bb[0],bb[1]),(bb[2],bb[3]),color=(random.randint(0,255),random.randint(0,255),random.randint(0,255))) cv2.imwrite(os.path.join(results_dir, "bounding_box_image.png"), image) f = open(os.path.join(results_dir,"bbs.csv"),"w") f.write("filename,xmin,ymin,xmax,ymax\n") for bb in bbs: f.write("%s,%s,%s,%s,%s\n"%(params["image_file"],bb[0],bb[1],bb[2],bb[3])) f.close()
h = round(pow(self.base_log, size_idx // self.edge_log_range + self.min_edge_log)) if (h > img_h * self.base_log) or (w > img_w * self.base_log): continue h = min(h, img_h) w = min(w, img_w)
random_line_split
area120tables_v1alpha1_generated_tables_service_list_tables_async.py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # 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. # # Generated code. DO NOT EDIT! # # Snippet for ListTables # NOTE: This snippet has been automatically generated for illustrative purposes only. # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: # python3 -m pip install google-area120-tables # [START area120tables_v1alpha1_generated_TablesService_ListTables_async] from google.area120 import tables_v1alpha1 async def sample_list_tables(): # Create a client
# [END area120tables_v1alpha1_generated_TablesService_ListTables_async]
client = tables_v1alpha1.TablesServiceAsyncClient() # Initialize request argument(s) request = tables_v1alpha1.ListTablesRequest( ) # Make the request page_result = client.list_tables(request=request) # Handle the response async for response in page_result: print(response)
identifier_body
area120tables_v1alpha1_generated_tables_service_list_tables_async.py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # 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. # # Generated code. DO NOT EDIT! # # Snippet for ListTables # NOTE: This snippet has been automatically generated for illustrative purposes only. # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: # python3 -m pip install google-area120-tables # [START area120tables_v1alpha1_generated_TablesService_ListTables_async] from google.area120 import tables_v1alpha1 async def
(): # Create a client client = tables_v1alpha1.TablesServiceAsyncClient() # Initialize request argument(s) request = tables_v1alpha1.ListTablesRequest( ) # Make the request page_result = client.list_tables(request=request) # Handle the response async for response in page_result: print(response) # [END area120tables_v1alpha1_generated_TablesService_ListTables_async]
sample_list_tables
identifier_name
area120tables_v1alpha1_generated_tables_service_list_tables_async.py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # 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.
# Snippet for ListTables # NOTE: This snippet has been automatically generated for illustrative purposes only. # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: # python3 -m pip install google-area120-tables # [START area120tables_v1alpha1_generated_TablesService_ListTables_async] from google.area120 import tables_v1alpha1 async def sample_list_tables(): # Create a client client = tables_v1alpha1.TablesServiceAsyncClient() # Initialize request argument(s) request = tables_v1alpha1.ListTablesRequest( ) # Make the request page_result = client.list_tables(request=request) # Handle the response async for response in page_result: print(response) # [END area120tables_v1alpha1_generated_TablesService_ListTables_async]
# See the License for the specific language governing permissions and # limitations under the License. # # Generated code. DO NOT EDIT! #
random_line_split
area120tables_v1alpha1_generated_tables_service_list_tables_async.py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # 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. # # Generated code. DO NOT EDIT! # # Snippet for ListTables # NOTE: This snippet has been automatically generated for illustrative purposes only. # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: # python3 -m pip install google-area120-tables # [START area120tables_v1alpha1_generated_TablesService_ListTables_async] from google.area120 import tables_v1alpha1 async def sample_list_tables(): # Create a client client = tables_v1alpha1.TablesServiceAsyncClient() # Initialize request argument(s) request = tables_v1alpha1.ListTablesRequest( ) # Make the request page_result = client.list_tables(request=request) # Handle the response async for response in page_result:
# [END area120tables_v1alpha1_generated_TablesService_ListTables_async]
print(response)
conditional_block
encoding.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as iconv from 'iconv-lite'; import { isLinux, isMacintosh } from 'vs/base/common/platform'; import { exec } from 'child_process'; import { Readable, Writable } from 'stream'; import { VSBuffer } from 'vs/base/common/buffer'; export const UTF8 = 'utf8'; export const UTF8_with_bom = 'utf8bom'; export const UTF16be = 'utf16be'; export const UTF16le = 'utf16le'; export const UTF16be_BOM = [0xFE, 0xFF]; export const UTF16le_BOM = [0xFF, 0xFE]; export const UTF8_BOM = [0xEF, 0xBB, 0xBF]; const ZERO_BYTE_DETECTION_BUFFER_MAX_LEN = 512; // number of bytes to look at to decide about a file being binary or not const NO_GUESS_BUFFER_MAX_LEN = 512; // when not auto guessing the encoding, small number of bytes are enough const AUTO_GUESS_BUFFER_MAX_LEN = 512 * 8; // with auto guessing we want a lot more content to be read for guessing export interface IDecodeStreamOptions { guessEncoding: boolean; minBytesRequiredForDetection?: number; overwriteEncoding(detectedEncoding: string | null): string; } export interface IDecodeStreamResult { stream: NodeJS.ReadableStream; detected: IDetectedEncodingResult; } export function toDecodeStream(readable: Readable, options: IDecodeStreamOptions): Promise<IDecodeStreamResult> { if (!options.minBytesRequiredForDetection) { options.minBytesRequiredForDetection = options.guessEncoding ? AUTO_GUESS_BUFFER_MAX_LEN : NO_GUESS_BUFFER_MAX_LEN; } return new Promise<IDecodeStreamResult>((resolve, reject) => { const writer = new class extends Writable { private decodeStream: NodeJS.ReadWriteStream; private decodeStreamPromise: Promise<void>; private bufferedChunks: Buffer[] = []; private bytesBuffered = 0; _write(chunk: Buffer, encoding: string, callback: (error: Error | null) => void): void { if (!Buffer.isBuffer(chunk)) { return callback(new Error('toDecodeStream(): data must be a buffer')); } // if the decode stream is ready, we just write directly if (this.decodeStream) { this.decodeStream.write(chunk, callback); return; } // otherwise we need to buffer the data until the stream is ready this.bufferedChunks.push(chunk); this.bytesBuffered += chunk.byteLength; // waiting for the decoder to be ready if (this.decodeStreamPromise) { this.decodeStreamPromise.then(() => callback(null), error => callback(error)); } // buffered enough data for encoding detection, create stream and forward data else if (typeof options.minBytesRequiredForDetection === 'number' && this.bytesBuffered >= options.minBytesRequiredForDetection) { this._startDecodeStream(callback); } // only buffering until enough data for encoding detection is there else { callback(null); } } _startDecodeStream(callback: (error: Error | null) => void): void { // detect encoding from buffer this.decodeStreamPromise = Promise.resolve(detectEncodingFromBuffer({ buffer: Buffer.concat(this.bufferedChunks), bytesRead: this.bytesBuffered }, options.guessEncoding)).then(detected => { // ensure to respect overwrite of encoding detected.encoding = options.overwriteEncoding(detected.encoding); // decode and write buffer this.decodeStream = decodeStream(detected.encoding); this.decodeStream.write(Buffer.concat(this.bufferedChunks), callback); this.bufferedChunks.length = 0;
}, error => { this.emit('error', error); callback(error); }); } _final(callback: (error: Error | null) => void) { // normal finish if (this.decodeStream) { this.decodeStream.end(callback); } // we were still waiting for data to do the encoding // detection. thus, wrap up starting the stream even // without all the data to get things going else { this._startDecodeStream(() => this.decodeStream.end(callback)); } } }; // errors readable.on('error', reject); // pipe through readable.pipe(writer); }); } export function decode(buffer: Buffer, encoding: string): string { return iconv.decode(buffer, toNodeEncoding(encoding)); } export function encode(content: string | Buffer, encoding: string, options?: { addBOM?: boolean }): Buffer { return iconv.encode(content, toNodeEncoding(encoding), options); } export function encodingExists(encoding: string): boolean { return iconv.encodingExists(toNodeEncoding(encoding)); } function decodeStream(encoding: string | null): NodeJS.ReadWriteStream { return iconv.decodeStream(toNodeEncoding(encoding)); } export function encodeStream(encoding: string, options?: { addBOM?: boolean }): NodeJS.ReadWriteStream { return iconv.encodeStream(toNodeEncoding(encoding), options); } function toNodeEncoding(enc: string | null): string { if (enc === UTF8_with_bom || enc === null) { return UTF8; // iconv does not distinguish UTF 8 with or without BOM, so we need to help it } return enc; } export function detectEncodingByBOMFromBuffer(buffer: Buffer | VSBuffer | null, bytesRead: number): string | null { if (!buffer || bytesRead < UTF16be_BOM.length) { return null; } const b0 = buffer.readUInt8(0); const b1 = buffer.readUInt8(1); // UTF-16 BE if (b0 === UTF16be_BOM[0] && b1 === UTF16be_BOM[1]) { return UTF16be; } // UTF-16 LE if (b0 === UTF16le_BOM[0] && b1 === UTF16le_BOM[1]) { return UTF16le; } if (bytesRead < UTF8_BOM.length) { return null; } const b2 = buffer.readUInt8(2); // UTF-8 if (b0 === UTF8_BOM[0] && b1 === UTF8_BOM[1] && b2 === UTF8_BOM[2]) { return UTF8; } return null; } const MINIMUM_THRESHOLD = 0.2; const IGNORE_ENCODINGS = ['ascii', 'utf-8', 'utf-16', 'utf-32']; /** * Guesses the encoding from buffer. */ async function guessEncodingByBuffer(buffer: Buffer): Promise<string | null> { const jschardet = await import('jschardet'); jschardet.Constants.MINIMUM_THRESHOLD = MINIMUM_THRESHOLD; const guessed = jschardet.detect(buffer); if (!guessed || !guessed.encoding) { return null; } const enc = guessed.encoding.toLowerCase(); // Ignore encodings that cannot guess correctly // (http://chardet.readthedocs.io/en/latest/supported-encodings.html) if (0 <= IGNORE_ENCODINGS.indexOf(enc)) { return null; } return toIconvLiteEncoding(guessed.encoding); } const JSCHARDET_TO_ICONV_ENCODINGS: { [name: string]: string } = { 'ibm866': 'cp866', 'big5': 'cp950' }; function toIconvLiteEncoding(encodingName: string): string { const normalizedEncodingName = encodingName.replace(/[^a-zA-Z0-9]/g, '').toLowerCase(); const mapped = JSCHARDET_TO_ICONV_ENCODINGS[normalizedEncodingName]; return mapped || normalizedEncodingName; } /** * The encodings that are allowed in a settings file don't match the canonical encoding labels specified by WHATWG. * See https://encoding.spec.whatwg.org/#names-and-labels * Iconv-lite strips all non-alphanumeric characters, but ripgrep doesn't. For backcompat, allow these labels. */ export function toCanonicalName(enc: string): string { switch (enc) { case 'shiftjis': return 'shift-jis'; case 'utf16le': return 'utf-16le'; case 'utf16be': return 'utf-16be'; case 'big5hkscs': return 'big5-hkscs'; case 'eucjp': return 'euc-jp'; case 'euckr': return 'euc-kr'; case 'koi8r': return 'koi8-r'; case 'koi8u': return 'koi8-u'; case 'macroman': return 'x-mac-roman'; case 'utf8bom': return 'utf8'; default: const m = enc.match(/windows(\d+)/); if (m) { return 'windows-' + m[1]; } return enc; } } export interface IDetectedEncodingResult { encoding: string | null; seemsBinary: boolean; } export interface IReadResult { buffer: Buffer | null; bytesRead: number; } export function detectEncodingFromBuffer(readResult: IReadResult, autoGuessEncoding?: false): IDetectedEncodingResult; export function detectEncodingFromBuffer(readResult: IReadResult, autoGuessEncoding?: boolean): Promise<IDetectedEncodingResult>; export function detectEncodingFromBuffer({ buffer, bytesRead }: IReadResult, autoGuessEncoding?: boolean): Promise<IDetectedEncodingResult> | IDetectedEncodingResult { // Always first check for BOM to find out about encoding let encoding = detectEncodingByBOMFromBuffer(buffer, bytesRead); // Detect 0 bytes to see if file is binary or UTF-16 LE/BE // unless we already know that this file has a UTF-16 encoding let seemsBinary = false; if (encoding !== UTF16be && encoding !== UTF16le && buffer) { let couldBeUTF16LE = true; // e.g. 0xAA 0x00 let couldBeUTF16BE = true; // e.g. 0x00 0xAA let containsZeroByte = false; // This is a simplified guess to detect UTF-16 BE or LE by just checking if // the first 512 bytes have the 0-byte at a specific location. For UTF-16 LE // this would be the odd byte index and for UTF-16 BE the even one. // Note: this can produce false positives (a binary file that uses a 2-byte // encoding of the same format as UTF-16) and false negatives (a UTF-16 file // that is using 4 bytes to encode a character). for (let i = 0; i < bytesRead && i < ZERO_BYTE_DETECTION_BUFFER_MAX_LEN; i++) { const isEndian = (i % 2 === 1); // assume 2-byte sequences typical for UTF-16 const isZeroByte = (buffer.readInt8(i) === 0); if (isZeroByte) { containsZeroByte = true; } // UTF-16 LE: expect e.g. 0xAA 0x00 if (couldBeUTF16LE && (isEndian && !isZeroByte || !isEndian && isZeroByte)) { couldBeUTF16LE = false; } // UTF-16 BE: expect e.g. 0x00 0xAA if (couldBeUTF16BE && (isEndian && isZeroByte || !isEndian && !isZeroByte)) { couldBeUTF16BE = false; } // Return if this is neither UTF16-LE nor UTF16-BE and thus treat as binary if (isZeroByte && !couldBeUTF16LE && !couldBeUTF16BE) { break; } } // Handle case of 0-byte included if (containsZeroByte) { if (couldBeUTF16LE) { encoding = UTF16le; } else if (couldBeUTF16BE) { encoding = UTF16be; } else { seemsBinary = true; } } } // Auto guess encoding if configured if (autoGuessEncoding && !seemsBinary && !encoding && buffer) { return guessEncodingByBuffer(buffer.slice(0, bytesRead)).then(guessedEncoding => { return { seemsBinary: false, encoding: guessedEncoding }; }); } return { seemsBinary, encoding }; } // https://ss64.com/nt/chcp.html const windowsTerminalEncodings = { '437': 'cp437', // United States '850': 'cp850', // Multilingual(Latin I) '852': 'cp852', // Slavic(Latin II) '855': 'cp855', // Cyrillic(Russian) '857': 'cp857', // Turkish '860': 'cp860', // Portuguese '861': 'cp861', // Icelandic '863': 'cp863', // Canadian - French '865': 'cp865', // Nordic '866': 'cp866', // Russian '869': 'cp869', // Modern Greek '936': 'cp936', // Simplified Chinese '1252': 'cp1252' // West European Latin }; export async function resolveTerminalEncoding(verbose?: boolean): Promise<string> { let rawEncodingPromise: Promise<string>; // Support a global environment variable to win over other mechanics const cliEncodingEnv = process.env['VSCODE_CLI_ENCODING']; if (cliEncodingEnv) { if (verbose) { console.log(`Found VSCODE_CLI_ENCODING variable: ${cliEncodingEnv}`); } rawEncodingPromise = Promise.resolve(cliEncodingEnv); } // Linux/Mac: use "locale charmap" command else if (isLinux || isMacintosh) { rawEncodingPromise = new Promise<string>(resolve => { if (verbose) { console.log('Running "locale charmap" to detect terminal encoding...'); } exec('locale charmap', (err, stdout, stderr) => resolve(stdout)); }); } // Windows: educated guess else { rawEncodingPromise = new Promise<string>(resolve => { if (verbose) { console.log('Running "chcp" to detect terminal encoding...'); } exec('chcp', (err, stdout, stderr) => { if (stdout) { const windowsTerminalEncodingKeys = Object.keys(windowsTerminalEncodings) as Array<keyof typeof windowsTerminalEncodings>; for (const key of windowsTerminalEncodingKeys) { if (stdout.indexOf(key) >= 0) { return resolve(windowsTerminalEncodings[key]); } } } return resolve(undefined); }); }); } const rawEncoding = await rawEncodingPromise; if (verbose) { console.log(`Detected raw terminal encoding: ${rawEncoding}`); } if (!rawEncoding || rawEncoding.toLowerCase() === 'utf-8' || rawEncoding.toLowerCase() === UTF8) { return UTF8; } const iconvEncoding = toIconvLiteEncoding(rawEncoding); if (iconv.encodingExists(iconvEncoding)) { return iconvEncoding; } if (verbose) { console.log('Unsupported terminal encoding, falling back to UTF-8.'); } return UTF8; }
// signal to the outside our detected encoding // and final decoder stream resolve({ detected, stream: this.decodeStream });
random_line_split
encoding.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as iconv from 'iconv-lite'; import { isLinux, isMacintosh } from 'vs/base/common/platform'; import { exec } from 'child_process'; import { Readable, Writable } from 'stream'; import { VSBuffer } from 'vs/base/common/buffer'; export const UTF8 = 'utf8'; export const UTF8_with_bom = 'utf8bom'; export const UTF16be = 'utf16be'; export const UTF16le = 'utf16le'; export const UTF16be_BOM = [0xFE, 0xFF]; export const UTF16le_BOM = [0xFF, 0xFE]; export const UTF8_BOM = [0xEF, 0xBB, 0xBF]; const ZERO_BYTE_DETECTION_BUFFER_MAX_LEN = 512; // number of bytes to look at to decide about a file being binary or not const NO_GUESS_BUFFER_MAX_LEN = 512; // when not auto guessing the encoding, small number of bytes are enough const AUTO_GUESS_BUFFER_MAX_LEN = 512 * 8; // with auto guessing we want a lot more content to be read for guessing export interface IDecodeStreamOptions { guessEncoding: boolean; minBytesRequiredForDetection?: number; overwriteEncoding(detectedEncoding: string | null): string; } export interface IDecodeStreamResult { stream: NodeJS.ReadableStream; detected: IDetectedEncodingResult; } export function toDecodeStream(readable: Readable, options: IDecodeStreamOptions): Promise<IDecodeStreamResult> { if (!options.minBytesRequiredForDetection) { options.minBytesRequiredForDetection = options.guessEncoding ? AUTO_GUESS_BUFFER_MAX_LEN : NO_GUESS_BUFFER_MAX_LEN; } return new Promise<IDecodeStreamResult>((resolve, reject) => { const writer = new class extends Writable { private decodeStream: NodeJS.ReadWriteStream; private decodeStreamPromise: Promise<void>; private bufferedChunks: Buffer[] = []; private bytesBuffered = 0;
(chunk: Buffer, encoding: string, callback: (error: Error | null) => void): void { if (!Buffer.isBuffer(chunk)) { return callback(new Error('toDecodeStream(): data must be a buffer')); } // if the decode stream is ready, we just write directly if (this.decodeStream) { this.decodeStream.write(chunk, callback); return; } // otherwise we need to buffer the data until the stream is ready this.bufferedChunks.push(chunk); this.bytesBuffered += chunk.byteLength; // waiting for the decoder to be ready if (this.decodeStreamPromise) { this.decodeStreamPromise.then(() => callback(null), error => callback(error)); } // buffered enough data for encoding detection, create stream and forward data else if (typeof options.minBytesRequiredForDetection === 'number' && this.bytesBuffered >= options.minBytesRequiredForDetection) { this._startDecodeStream(callback); } // only buffering until enough data for encoding detection is there else { callback(null); } } _startDecodeStream(callback: (error: Error | null) => void): void { // detect encoding from buffer this.decodeStreamPromise = Promise.resolve(detectEncodingFromBuffer({ buffer: Buffer.concat(this.bufferedChunks), bytesRead: this.bytesBuffered }, options.guessEncoding)).then(detected => { // ensure to respect overwrite of encoding detected.encoding = options.overwriteEncoding(detected.encoding); // decode and write buffer this.decodeStream = decodeStream(detected.encoding); this.decodeStream.write(Buffer.concat(this.bufferedChunks), callback); this.bufferedChunks.length = 0; // signal to the outside our detected encoding // and final decoder stream resolve({ detected, stream: this.decodeStream }); }, error => { this.emit('error', error); callback(error); }); } _final(callback: (error: Error | null) => void) { // normal finish if (this.decodeStream) { this.decodeStream.end(callback); } // we were still waiting for data to do the encoding // detection. thus, wrap up starting the stream even // without all the data to get things going else { this._startDecodeStream(() => this.decodeStream.end(callback)); } } }; // errors readable.on('error', reject); // pipe through readable.pipe(writer); }); } export function decode(buffer: Buffer, encoding: string): string { return iconv.decode(buffer, toNodeEncoding(encoding)); } export function encode(content: string | Buffer, encoding: string, options?: { addBOM?: boolean }): Buffer { return iconv.encode(content, toNodeEncoding(encoding), options); } export function encodingExists(encoding: string): boolean { return iconv.encodingExists(toNodeEncoding(encoding)); } function decodeStream(encoding: string | null): NodeJS.ReadWriteStream { return iconv.decodeStream(toNodeEncoding(encoding)); } export function encodeStream(encoding: string, options?: { addBOM?: boolean }): NodeJS.ReadWriteStream { return iconv.encodeStream(toNodeEncoding(encoding), options); } function toNodeEncoding(enc: string | null): string { if (enc === UTF8_with_bom || enc === null) { return UTF8; // iconv does not distinguish UTF 8 with or without BOM, so we need to help it } return enc; } export function detectEncodingByBOMFromBuffer(buffer: Buffer | VSBuffer | null, bytesRead: number): string | null { if (!buffer || bytesRead < UTF16be_BOM.length) { return null; } const b0 = buffer.readUInt8(0); const b1 = buffer.readUInt8(1); // UTF-16 BE if (b0 === UTF16be_BOM[0] && b1 === UTF16be_BOM[1]) { return UTF16be; } // UTF-16 LE if (b0 === UTF16le_BOM[0] && b1 === UTF16le_BOM[1]) { return UTF16le; } if (bytesRead < UTF8_BOM.length) { return null; } const b2 = buffer.readUInt8(2); // UTF-8 if (b0 === UTF8_BOM[0] && b1 === UTF8_BOM[1] && b2 === UTF8_BOM[2]) { return UTF8; } return null; } const MINIMUM_THRESHOLD = 0.2; const IGNORE_ENCODINGS = ['ascii', 'utf-8', 'utf-16', 'utf-32']; /** * Guesses the encoding from buffer. */ async function guessEncodingByBuffer(buffer: Buffer): Promise<string | null> { const jschardet = await import('jschardet'); jschardet.Constants.MINIMUM_THRESHOLD = MINIMUM_THRESHOLD; const guessed = jschardet.detect(buffer); if (!guessed || !guessed.encoding) { return null; } const enc = guessed.encoding.toLowerCase(); // Ignore encodings that cannot guess correctly // (http://chardet.readthedocs.io/en/latest/supported-encodings.html) if (0 <= IGNORE_ENCODINGS.indexOf(enc)) { return null; } return toIconvLiteEncoding(guessed.encoding); } const JSCHARDET_TO_ICONV_ENCODINGS: { [name: string]: string } = { 'ibm866': 'cp866', 'big5': 'cp950' }; function toIconvLiteEncoding(encodingName: string): string { const normalizedEncodingName = encodingName.replace(/[^a-zA-Z0-9]/g, '').toLowerCase(); const mapped = JSCHARDET_TO_ICONV_ENCODINGS[normalizedEncodingName]; return mapped || normalizedEncodingName; } /** * The encodings that are allowed in a settings file don't match the canonical encoding labels specified by WHATWG. * See https://encoding.spec.whatwg.org/#names-and-labels * Iconv-lite strips all non-alphanumeric characters, but ripgrep doesn't. For backcompat, allow these labels. */ export function toCanonicalName(enc: string): string { switch (enc) { case 'shiftjis': return 'shift-jis'; case 'utf16le': return 'utf-16le'; case 'utf16be': return 'utf-16be'; case 'big5hkscs': return 'big5-hkscs'; case 'eucjp': return 'euc-jp'; case 'euckr': return 'euc-kr'; case 'koi8r': return 'koi8-r'; case 'koi8u': return 'koi8-u'; case 'macroman': return 'x-mac-roman'; case 'utf8bom': return 'utf8'; default: const m = enc.match(/windows(\d+)/); if (m) { return 'windows-' + m[1]; } return enc; } } export interface IDetectedEncodingResult { encoding: string | null; seemsBinary: boolean; } export interface IReadResult { buffer: Buffer | null; bytesRead: number; } export function detectEncodingFromBuffer(readResult: IReadResult, autoGuessEncoding?: false): IDetectedEncodingResult; export function detectEncodingFromBuffer(readResult: IReadResult, autoGuessEncoding?: boolean): Promise<IDetectedEncodingResult>; export function detectEncodingFromBuffer({ buffer, bytesRead }: IReadResult, autoGuessEncoding?: boolean): Promise<IDetectedEncodingResult> | IDetectedEncodingResult { // Always first check for BOM to find out about encoding let encoding = detectEncodingByBOMFromBuffer(buffer, bytesRead); // Detect 0 bytes to see if file is binary or UTF-16 LE/BE // unless we already know that this file has a UTF-16 encoding let seemsBinary = false; if (encoding !== UTF16be && encoding !== UTF16le && buffer) { let couldBeUTF16LE = true; // e.g. 0xAA 0x00 let couldBeUTF16BE = true; // e.g. 0x00 0xAA let containsZeroByte = false; // This is a simplified guess to detect UTF-16 BE or LE by just checking if // the first 512 bytes have the 0-byte at a specific location. For UTF-16 LE // this would be the odd byte index and for UTF-16 BE the even one. // Note: this can produce false positives (a binary file that uses a 2-byte // encoding of the same format as UTF-16) and false negatives (a UTF-16 file // that is using 4 bytes to encode a character). for (let i = 0; i < bytesRead && i < ZERO_BYTE_DETECTION_BUFFER_MAX_LEN; i++) { const isEndian = (i % 2 === 1); // assume 2-byte sequences typical for UTF-16 const isZeroByte = (buffer.readInt8(i) === 0); if (isZeroByte) { containsZeroByte = true; } // UTF-16 LE: expect e.g. 0xAA 0x00 if (couldBeUTF16LE && (isEndian && !isZeroByte || !isEndian && isZeroByte)) { couldBeUTF16LE = false; } // UTF-16 BE: expect e.g. 0x00 0xAA if (couldBeUTF16BE && (isEndian && isZeroByte || !isEndian && !isZeroByte)) { couldBeUTF16BE = false; } // Return if this is neither UTF16-LE nor UTF16-BE and thus treat as binary if (isZeroByte && !couldBeUTF16LE && !couldBeUTF16BE) { break; } } // Handle case of 0-byte included if (containsZeroByte) { if (couldBeUTF16LE) { encoding = UTF16le; } else if (couldBeUTF16BE) { encoding = UTF16be; } else { seemsBinary = true; } } } // Auto guess encoding if configured if (autoGuessEncoding && !seemsBinary && !encoding && buffer) { return guessEncodingByBuffer(buffer.slice(0, bytesRead)).then(guessedEncoding => { return { seemsBinary: false, encoding: guessedEncoding }; }); } return { seemsBinary, encoding }; } // https://ss64.com/nt/chcp.html const windowsTerminalEncodings = { '437': 'cp437', // United States '850': 'cp850', // Multilingual(Latin I) '852': 'cp852', // Slavic(Latin II) '855': 'cp855', // Cyrillic(Russian) '857': 'cp857', // Turkish '860': 'cp860', // Portuguese '861': 'cp861', // Icelandic '863': 'cp863', // Canadian - French '865': 'cp865', // Nordic '866': 'cp866', // Russian '869': 'cp869', // Modern Greek '936': 'cp936', // Simplified Chinese '1252': 'cp1252' // West European Latin }; export async function resolveTerminalEncoding(verbose?: boolean): Promise<string> { let rawEncodingPromise: Promise<string>; // Support a global environment variable to win over other mechanics const cliEncodingEnv = process.env['VSCODE_CLI_ENCODING']; if (cliEncodingEnv) { if (verbose) { console.log(`Found VSCODE_CLI_ENCODING variable: ${cliEncodingEnv}`); } rawEncodingPromise = Promise.resolve(cliEncodingEnv); } // Linux/Mac: use "locale charmap" command else if (isLinux || isMacintosh) { rawEncodingPromise = new Promise<string>(resolve => { if (verbose) { console.log('Running "locale charmap" to detect terminal encoding...'); } exec('locale charmap', (err, stdout, stderr) => resolve(stdout)); }); } // Windows: educated guess else { rawEncodingPromise = new Promise<string>(resolve => { if (verbose) { console.log('Running "chcp" to detect terminal encoding...'); } exec('chcp', (err, stdout, stderr) => { if (stdout) { const windowsTerminalEncodingKeys = Object.keys(windowsTerminalEncodings) as Array<keyof typeof windowsTerminalEncodings>; for (const key of windowsTerminalEncodingKeys) { if (stdout.indexOf(key) >= 0) { return resolve(windowsTerminalEncodings[key]); } } } return resolve(undefined); }); }); } const rawEncoding = await rawEncodingPromise; if (verbose) { console.log(`Detected raw terminal encoding: ${rawEncoding}`); } if (!rawEncoding || rawEncoding.toLowerCase() === 'utf-8' || rawEncoding.toLowerCase() === UTF8) { return UTF8; } const iconvEncoding = toIconvLiteEncoding(rawEncoding); if (iconv.encodingExists(iconvEncoding)) { return iconvEncoding; } if (verbose) { console.log('Unsupported terminal encoding, falling back to UTF-8.'); } return UTF8; }
_write
identifier_name
encoding.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as iconv from 'iconv-lite'; import { isLinux, isMacintosh } from 'vs/base/common/platform'; import { exec } from 'child_process'; import { Readable, Writable } from 'stream'; import { VSBuffer } from 'vs/base/common/buffer'; export const UTF8 = 'utf8'; export const UTF8_with_bom = 'utf8bom'; export const UTF16be = 'utf16be'; export const UTF16le = 'utf16le'; export const UTF16be_BOM = [0xFE, 0xFF]; export const UTF16le_BOM = [0xFF, 0xFE]; export const UTF8_BOM = [0xEF, 0xBB, 0xBF]; const ZERO_BYTE_DETECTION_BUFFER_MAX_LEN = 512; // number of bytes to look at to decide about a file being binary or not const NO_GUESS_BUFFER_MAX_LEN = 512; // when not auto guessing the encoding, small number of bytes are enough const AUTO_GUESS_BUFFER_MAX_LEN = 512 * 8; // with auto guessing we want a lot more content to be read for guessing export interface IDecodeStreamOptions { guessEncoding: boolean; minBytesRequiredForDetection?: number; overwriteEncoding(detectedEncoding: string | null): string; } export interface IDecodeStreamResult { stream: NodeJS.ReadableStream; detected: IDetectedEncodingResult; } export function toDecodeStream(readable: Readable, options: IDecodeStreamOptions): Promise<IDecodeStreamResult> { if (!options.minBytesRequiredForDetection) { options.minBytesRequiredForDetection = options.guessEncoding ? AUTO_GUESS_BUFFER_MAX_LEN : NO_GUESS_BUFFER_MAX_LEN; } return new Promise<IDecodeStreamResult>((resolve, reject) => { const writer = new class extends Writable { private decodeStream: NodeJS.ReadWriteStream; private decodeStreamPromise: Promise<void>; private bufferedChunks: Buffer[] = []; private bytesBuffered = 0; _write(chunk: Buffer, encoding: string, callback: (error: Error | null) => void): void { if (!Buffer.isBuffer(chunk)) { return callback(new Error('toDecodeStream(): data must be a buffer')); } // if the decode stream is ready, we just write directly if (this.decodeStream) { this.decodeStream.write(chunk, callback); return; } // otherwise we need to buffer the data until the stream is ready this.bufferedChunks.push(chunk); this.bytesBuffered += chunk.byteLength; // waiting for the decoder to be ready if (this.decodeStreamPromise) { this.decodeStreamPromise.then(() => callback(null), error => callback(error)); } // buffered enough data for encoding detection, create stream and forward data else if (typeof options.minBytesRequiredForDetection === 'number' && this.bytesBuffered >= options.minBytesRequiredForDetection) { this._startDecodeStream(callback); } // only buffering until enough data for encoding detection is there else { callback(null); } } _startDecodeStream(callback: (error: Error | null) => void): void { // detect encoding from buffer this.decodeStreamPromise = Promise.resolve(detectEncodingFromBuffer({ buffer: Buffer.concat(this.bufferedChunks), bytesRead: this.bytesBuffered }, options.guessEncoding)).then(detected => { // ensure to respect overwrite of encoding detected.encoding = options.overwriteEncoding(detected.encoding); // decode and write buffer this.decodeStream = decodeStream(detected.encoding); this.decodeStream.write(Buffer.concat(this.bufferedChunks), callback); this.bufferedChunks.length = 0; // signal to the outside our detected encoding // and final decoder stream resolve({ detected, stream: this.decodeStream }); }, error => { this.emit('error', error); callback(error); }); } _final(callback: (error: Error | null) => void)
}; // errors readable.on('error', reject); // pipe through readable.pipe(writer); }); } export function decode(buffer: Buffer, encoding: string): string { return iconv.decode(buffer, toNodeEncoding(encoding)); } export function encode(content: string | Buffer, encoding: string, options?: { addBOM?: boolean }): Buffer { return iconv.encode(content, toNodeEncoding(encoding), options); } export function encodingExists(encoding: string): boolean { return iconv.encodingExists(toNodeEncoding(encoding)); } function decodeStream(encoding: string | null): NodeJS.ReadWriteStream { return iconv.decodeStream(toNodeEncoding(encoding)); } export function encodeStream(encoding: string, options?: { addBOM?: boolean }): NodeJS.ReadWriteStream { return iconv.encodeStream(toNodeEncoding(encoding), options); } function toNodeEncoding(enc: string | null): string { if (enc === UTF8_with_bom || enc === null) { return UTF8; // iconv does not distinguish UTF 8 with or without BOM, so we need to help it } return enc; } export function detectEncodingByBOMFromBuffer(buffer: Buffer | VSBuffer | null, bytesRead: number): string | null { if (!buffer || bytesRead < UTF16be_BOM.length) { return null; } const b0 = buffer.readUInt8(0); const b1 = buffer.readUInt8(1); // UTF-16 BE if (b0 === UTF16be_BOM[0] && b1 === UTF16be_BOM[1]) { return UTF16be; } // UTF-16 LE if (b0 === UTF16le_BOM[0] && b1 === UTF16le_BOM[1]) { return UTF16le; } if (bytesRead < UTF8_BOM.length) { return null; } const b2 = buffer.readUInt8(2); // UTF-8 if (b0 === UTF8_BOM[0] && b1 === UTF8_BOM[1] && b2 === UTF8_BOM[2]) { return UTF8; } return null; } const MINIMUM_THRESHOLD = 0.2; const IGNORE_ENCODINGS = ['ascii', 'utf-8', 'utf-16', 'utf-32']; /** * Guesses the encoding from buffer. */ async function guessEncodingByBuffer(buffer: Buffer): Promise<string | null> { const jschardet = await import('jschardet'); jschardet.Constants.MINIMUM_THRESHOLD = MINIMUM_THRESHOLD; const guessed = jschardet.detect(buffer); if (!guessed || !guessed.encoding) { return null; } const enc = guessed.encoding.toLowerCase(); // Ignore encodings that cannot guess correctly // (http://chardet.readthedocs.io/en/latest/supported-encodings.html) if (0 <= IGNORE_ENCODINGS.indexOf(enc)) { return null; } return toIconvLiteEncoding(guessed.encoding); } const JSCHARDET_TO_ICONV_ENCODINGS: { [name: string]: string } = { 'ibm866': 'cp866', 'big5': 'cp950' }; function toIconvLiteEncoding(encodingName: string): string { const normalizedEncodingName = encodingName.replace(/[^a-zA-Z0-9]/g, '').toLowerCase(); const mapped = JSCHARDET_TO_ICONV_ENCODINGS[normalizedEncodingName]; return mapped || normalizedEncodingName; } /** * The encodings that are allowed in a settings file don't match the canonical encoding labels specified by WHATWG. * See https://encoding.spec.whatwg.org/#names-and-labels * Iconv-lite strips all non-alphanumeric characters, but ripgrep doesn't. For backcompat, allow these labels. */ export function toCanonicalName(enc: string): string { switch (enc) { case 'shiftjis': return 'shift-jis'; case 'utf16le': return 'utf-16le'; case 'utf16be': return 'utf-16be'; case 'big5hkscs': return 'big5-hkscs'; case 'eucjp': return 'euc-jp'; case 'euckr': return 'euc-kr'; case 'koi8r': return 'koi8-r'; case 'koi8u': return 'koi8-u'; case 'macroman': return 'x-mac-roman'; case 'utf8bom': return 'utf8'; default: const m = enc.match(/windows(\d+)/); if (m) { return 'windows-' + m[1]; } return enc; } } export interface IDetectedEncodingResult { encoding: string | null; seemsBinary: boolean; } export interface IReadResult { buffer: Buffer | null; bytesRead: number; } export function detectEncodingFromBuffer(readResult: IReadResult, autoGuessEncoding?: false): IDetectedEncodingResult; export function detectEncodingFromBuffer(readResult: IReadResult, autoGuessEncoding?: boolean): Promise<IDetectedEncodingResult>; export function detectEncodingFromBuffer({ buffer, bytesRead }: IReadResult, autoGuessEncoding?: boolean): Promise<IDetectedEncodingResult> | IDetectedEncodingResult { // Always first check for BOM to find out about encoding let encoding = detectEncodingByBOMFromBuffer(buffer, bytesRead); // Detect 0 bytes to see if file is binary or UTF-16 LE/BE // unless we already know that this file has a UTF-16 encoding let seemsBinary = false; if (encoding !== UTF16be && encoding !== UTF16le && buffer) { let couldBeUTF16LE = true; // e.g. 0xAA 0x00 let couldBeUTF16BE = true; // e.g. 0x00 0xAA let containsZeroByte = false; // This is a simplified guess to detect UTF-16 BE or LE by just checking if // the first 512 bytes have the 0-byte at a specific location. For UTF-16 LE // this would be the odd byte index and for UTF-16 BE the even one. // Note: this can produce false positives (a binary file that uses a 2-byte // encoding of the same format as UTF-16) and false negatives (a UTF-16 file // that is using 4 bytes to encode a character). for (let i = 0; i < bytesRead && i < ZERO_BYTE_DETECTION_BUFFER_MAX_LEN; i++) { const isEndian = (i % 2 === 1); // assume 2-byte sequences typical for UTF-16 const isZeroByte = (buffer.readInt8(i) === 0); if (isZeroByte) { containsZeroByte = true; } // UTF-16 LE: expect e.g. 0xAA 0x00 if (couldBeUTF16LE && (isEndian && !isZeroByte || !isEndian && isZeroByte)) { couldBeUTF16LE = false; } // UTF-16 BE: expect e.g. 0x00 0xAA if (couldBeUTF16BE && (isEndian && isZeroByte || !isEndian && !isZeroByte)) { couldBeUTF16BE = false; } // Return if this is neither UTF16-LE nor UTF16-BE and thus treat as binary if (isZeroByte && !couldBeUTF16LE && !couldBeUTF16BE) { break; } } // Handle case of 0-byte included if (containsZeroByte) { if (couldBeUTF16LE) { encoding = UTF16le; } else if (couldBeUTF16BE) { encoding = UTF16be; } else { seemsBinary = true; } } } // Auto guess encoding if configured if (autoGuessEncoding && !seemsBinary && !encoding && buffer) { return guessEncodingByBuffer(buffer.slice(0, bytesRead)).then(guessedEncoding => { return { seemsBinary: false, encoding: guessedEncoding }; }); } return { seemsBinary, encoding }; } // https://ss64.com/nt/chcp.html const windowsTerminalEncodings = { '437': 'cp437', // United States '850': 'cp850', // Multilingual(Latin I) '852': 'cp852', // Slavic(Latin II) '855': 'cp855', // Cyrillic(Russian) '857': 'cp857', // Turkish '860': 'cp860', // Portuguese '861': 'cp861', // Icelandic '863': 'cp863', // Canadian - French '865': 'cp865', // Nordic '866': 'cp866', // Russian '869': 'cp869', // Modern Greek '936': 'cp936', // Simplified Chinese '1252': 'cp1252' // West European Latin }; export async function resolveTerminalEncoding(verbose?: boolean): Promise<string> { let rawEncodingPromise: Promise<string>; // Support a global environment variable to win over other mechanics const cliEncodingEnv = process.env['VSCODE_CLI_ENCODING']; if (cliEncodingEnv) { if (verbose) { console.log(`Found VSCODE_CLI_ENCODING variable: ${cliEncodingEnv}`); } rawEncodingPromise = Promise.resolve(cliEncodingEnv); } // Linux/Mac: use "locale charmap" command else if (isLinux || isMacintosh) { rawEncodingPromise = new Promise<string>(resolve => { if (verbose) { console.log('Running "locale charmap" to detect terminal encoding...'); } exec('locale charmap', (err, stdout, stderr) => resolve(stdout)); }); } // Windows: educated guess else { rawEncodingPromise = new Promise<string>(resolve => { if (verbose) { console.log('Running "chcp" to detect terminal encoding...'); } exec('chcp', (err, stdout, stderr) => { if (stdout) { const windowsTerminalEncodingKeys = Object.keys(windowsTerminalEncodings) as Array<keyof typeof windowsTerminalEncodings>; for (const key of windowsTerminalEncodingKeys) { if (stdout.indexOf(key) >= 0) { return resolve(windowsTerminalEncodings[key]); } } } return resolve(undefined); }); }); } const rawEncoding = await rawEncodingPromise; if (verbose) { console.log(`Detected raw terminal encoding: ${rawEncoding}`); } if (!rawEncoding || rawEncoding.toLowerCase() === 'utf-8' || rawEncoding.toLowerCase() === UTF8) { return UTF8; } const iconvEncoding = toIconvLiteEncoding(rawEncoding); if (iconv.encodingExists(iconvEncoding)) { return iconvEncoding; } if (verbose) { console.log('Unsupported terminal encoding, falling back to UTF-8.'); } return UTF8; }
{ // normal finish if (this.decodeStream) { this.decodeStream.end(callback); } // we were still waiting for data to do the encoding // detection. thus, wrap up starting the stream even // without all the data to get things going else { this._startDecodeStream(() => this.decodeStream.end(callback)); } }
identifier_body
index.js
var http = require("http"); var fs = require("fs"); var handlerNames = fs.readdirSync("./handlers"); handlerNames = handlerNames.map(function(file){return file.replace(".js", "")}); var argv = require('yargs') .usage('Usage: $0 <command> [options]') .demand('handler') .describe('handler', 'Choose a handler to run tests against. Available handlers:' + handlerNames.join(", ")) .argv; var baseTime = 5000; // ms var additionalTimePerQuery = 200; // ms var pendingQueries = 0; var timestamp = function(){ return new Date().toISOString().replace('T', ' ').replace('Z', ''); } var workFunction = function(callback){ var delay = baseTime + (additionalTimePerQuery * pendingQueries); pendingQueries += 1; console.log(timestamp() + "\tWork Starting. Pending:\t" + pendingQueries + " Delay: " + delay); setTimeout(function(){ callback(null, "Hello World"); pendingQueries -= 1; console.log(timestamp() + "\tWork Finished. Pending:\t", pendingQueries); }, delay) } var handler; if(handlerNames.indexOf(argv.handler) !== -1){ handler = require("./handlers/" + argv.handler); }else{ throw new Error("Unknown handler '"+argv.handler+"'. Available Handlers: " + handlerNames.join(", ")) } var logMemory = function(){ console.log(timestamp() + "\t" + (process.memoryUsage().rss/(1024*1024)).toFixed(2) + " MB"); } setInterval(logMemory, 5000); if(typeof handler === "undefined"){ throw new Error("Unknown handler chosen"); } function handleRequest(request, response)
var port = 8002; var server = http.createServer(handleRequest); server.listen(port, function () { console.log("Listening on: http://127.0.01:%s", port); });
{ handler(workFunction, function(err, data){ response.end(data); }); }
identifier_body
index.js
var http = require("http"); var fs = require("fs"); var handlerNames = fs.readdirSync("./handlers"); handlerNames = handlerNames.map(function(file){return file.replace(".js", "")}); var argv = require('yargs') .usage('Usage: $0 <command> [options]') .demand('handler') .describe('handler', 'Choose a handler to run tests against. Available handlers:' + handlerNames.join(", ")) .argv; var baseTime = 5000; // ms var additionalTimePerQuery = 200; // ms var pendingQueries = 0; var timestamp = function(){ return new Date().toISOString().replace('T', ' ').replace('Z', '');
var workFunction = function(callback){ var delay = baseTime + (additionalTimePerQuery * pendingQueries); pendingQueries += 1; console.log(timestamp() + "\tWork Starting. Pending:\t" + pendingQueries + " Delay: " + delay); setTimeout(function(){ callback(null, "Hello World"); pendingQueries -= 1; console.log(timestamp() + "\tWork Finished. Pending:\t", pendingQueries); }, delay) } var handler; if(handlerNames.indexOf(argv.handler) !== -1){ handler = require("./handlers/" + argv.handler); }else{ throw new Error("Unknown handler '"+argv.handler+"'. Available Handlers: " + handlerNames.join(", ")) } var logMemory = function(){ console.log(timestamp() + "\t" + (process.memoryUsage().rss/(1024*1024)).toFixed(2) + " MB"); } setInterval(logMemory, 5000); if(typeof handler === "undefined"){ throw new Error("Unknown handler chosen"); } function handleRequest(request, response) { handler(workFunction, function(err, data){ response.end(data); }); } var port = 8002; var server = http.createServer(handleRequest); server.listen(port, function () { console.log("Listening on: http://127.0.01:%s", port); });
}
random_line_split
index.js
var http = require("http"); var fs = require("fs"); var handlerNames = fs.readdirSync("./handlers"); handlerNames = handlerNames.map(function(file){return file.replace(".js", "")}); var argv = require('yargs') .usage('Usage: $0 <command> [options]') .demand('handler') .describe('handler', 'Choose a handler to run tests against. Available handlers:' + handlerNames.join(", ")) .argv; var baseTime = 5000; // ms var additionalTimePerQuery = 200; // ms var pendingQueries = 0; var timestamp = function(){ return new Date().toISOString().replace('T', ' ').replace('Z', ''); } var workFunction = function(callback){ var delay = baseTime + (additionalTimePerQuery * pendingQueries); pendingQueries += 1; console.log(timestamp() + "\tWork Starting. Pending:\t" + pendingQueries + " Delay: " + delay); setTimeout(function(){ callback(null, "Hello World"); pendingQueries -= 1; console.log(timestamp() + "\tWork Finished. Pending:\t", pendingQueries); }, delay) } var handler; if(handlerNames.indexOf(argv.handler) !== -1){ handler = require("./handlers/" + argv.handler); }else
var logMemory = function(){ console.log(timestamp() + "\t" + (process.memoryUsage().rss/(1024*1024)).toFixed(2) + " MB"); } setInterval(logMemory, 5000); if(typeof handler === "undefined"){ throw new Error("Unknown handler chosen"); } function handleRequest(request, response) { handler(workFunction, function(err, data){ response.end(data); }); } var port = 8002; var server = http.createServer(handleRequest); server.listen(port, function () { console.log("Listening on: http://127.0.01:%s", port); });
{ throw new Error("Unknown handler '"+argv.handler+"'. Available Handlers: " + handlerNames.join(", ")) }
conditional_block
index.js
var http = require("http"); var fs = require("fs"); var handlerNames = fs.readdirSync("./handlers"); handlerNames = handlerNames.map(function(file){return file.replace(".js", "")}); var argv = require('yargs') .usage('Usage: $0 <command> [options]') .demand('handler') .describe('handler', 'Choose a handler to run tests against. Available handlers:' + handlerNames.join(", ")) .argv; var baseTime = 5000; // ms var additionalTimePerQuery = 200; // ms var pendingQueries = 0; var timestamp = function(){ return new Date().toISOString().replace('T', ' ').replace('Z', ''); } var workFunction = function(callback){ var delay = baseTime + (additionalTimePerQuery * pendingQueries); pendingQueries += 1; console.log(timestamp() + "\tWork Starting. Pending:\t" + pendingQueries + " Delay: " + delay); setTimeout(function(){ callback(null, "Hello World"); pendingQueries -= 1; console.log(timestamp() + "\tWork Finished. Pending:\t", pendingQueries); }, delay) } var handler; if(handlerNames.indexOf(argv.handler) !== -1){ handler = require("./handlers/" + argv.handler); }else{ throw new Error("Unknown handler '"+argv.handler+"'. Available Handlers: " + handlerNames.join(", ")) } var logMemory = function(){ console.log(timestamp() + "\t" + (process.memoryUsage().rss/(1024*1024)).toFixed(2) + " MB"); } setInterval(logMemory, 5000); if(typeof handler === "undefined"){ throw new Error("Unknown handler chosen"); } function
(request, response) { handler(workFunction, function(err, data){ response.end(data); }); } var port = 8002; var server = http.createServer(handleRequest); server.listen(port, function () { console.log("Listening on: http://127.0.01:%s", port); });
handleRequest
identifier_name
custom-mode-characteristics.component.ts
import { Component } from '@angular/core'; import { CustomModeCharacteristicsService } from './custom-mode-characteristics.service'; import { ChordCharacteristics } from './chord-characteristics'; import { Router } from '@angular/router'; @Component({ selector: 'custom-mode-characteristics', templateUrl: 'app/custom-mode-characteristics.html', styleUrls: ['app/custom-mode-characteristics.css'], providers: [CustomModeCharacteristicsService] }) // The view for selecting chord characteristics that will be tested in custom // mode. export class CustomModeCharacteristics { private selectedChordQualities: Map<string, boolean> = new Map<string, boolean>(); private selectedChordInversions: Map<string, boolean> = new Map<string, boolean>(); private allChordCharacteristics: ChordCharacteristics = new ChordCharacteristics(); constructor(private customModeCharacteristicsService: CustomModeCharacteristicsService, private router : Router) {} ngOnInit() { this.customModeCharacteristicsService.getCustomModeChordCharacteristics() .then(characteristics => this.initializeChordCharacteristics(characteristics)) .catch(error => window.alert(error._body)); } // Initializes the chord characteristics data structures in this class after // they are received from the server. private initializeChordCharacteristics(chordCharacteristics : ChordCharacteristics) { this.allChordCharacteristics = chordCharacteristics; // Adding all chord characteristics to the specific maps of selected // characteristics. this.selectedChordQualities = new Map<string, boolean>(); this.selectedChordInversions = new Map<string, boolean>(); for (let q of this.allChordCharacteristics.trainerChordQualities) { this.selectedChordQualities.set(q, false); } for (let i of this.allChordCharacteristics.trainerChordInversions) { this.selectedChordInversions.set(i, false); } } onChordQualitySelected(quality: string) { //Setting or unsetting a chord quality in the selected characteristics. let isSet = this.selectedChordQualities.get(quality); if (isSet === undefined) { // If it can't find the value, then there is a bug. window.alert("Cannot select chord quality"); return; } else
} onChordInversionSelected(inversion: string) { //Setting or unsetting a chord inversion in the selected characteristics. let isSet = this.selectedChordInversions.get(inversion); if (isSet === undefined) { // If it can't find the value, then there is a bug. window.alert("Cannot select chord inversion"); return; } else { this.selectedChordInversions.set(inversion, !isSet); } } onStartTrainerButtonSelected() { // Building an array of selected chord qualities. If none were selected, // then all are available to be tested on and they are added to the array. let chordQualities: string[] = [ ]; this.selectedChordQualities.forEach(function(value, key, map){ if (value === true) { chordQualities.push(key); } }); if (chordQualities.length === 0) { chordQualities = this.allChordCharacteristics.trainerChordQualities; } // Building an array of selected chord inversions. If none were selected, // then all are available to be tested on and they are added to the array. let chordInversions: string[] = [ ]; this.selectedChordInversions.forEach(function(value, key, map){ if (value === true) { chordInversions.push(key); } }); if (chordInversions.length === 0) { chordInversions = this.allChordCharacteristics.trainerChordInversions; } let chordCharacteristics: ChordCharacteristics = new ChordCharacteristics(chordQualities, chordInversions); this.router.navigate(['/chordTester', chordCharacteristics]); } }
{ this.selectedChordQualities.set(quality, !isSet); }
conditional_block
custom-mode-characteristics.component.ts
import { Component } from '@angular/core'; import { CustomModeCharacteristicsService } from './custom-mode-characteristics.service'; import { ChordCharacteristics } from './chord-characteristics'; import { Router } from '@angular/router'; @Component({ selector: 'custom-mode-characteristics', templateUrl: 'app/custom-mode-characteristics.html', styleUrls: ['app/custom-mode-characteristics.css'], providers: [CustomModeCharacteristicsService] }) // The view for selecting chord characteristics that will be tested in custom // mode. export class CustomModeCharacteristics { private selectedChordQualities: Map<string, boolean> = new Map<string, boolean>(); private selectedChordInversions: Map<string, boolean> = new Map<string, boolean>(); private allChordCharacteristics: ChordCharacteristics = new ChordCharacteristics(); constructor(private customModeCharacteristicsService: CustomModeCharacteristicsService, private router : Router) {} ngOnInit() { this.customModeCharacteristicsService.getCustomModeChordCharacteristics() .then(characteristics => this.initializeChordCharacteristics(characteristics)) .catch(error => window.alert(error._body)); } // Initializes the chord characteristics data structures in this class after // they are received from the server. private initializeChordCharacteristics(chordCharacteristics : ChordCharacteristics) { this.allChordCharacteristics = chordCharacteristics; // Adding all chord characteristics to the specific maps of selected // characteristics. this.selectedChordQualities = new Map<string, boolean>(); this.selectedChordInversions = new Map<string, boolean>(); for (let q of this.allChordCharacteristics.trainerChordQualities) { this.selectedChordQualities.set(q, false); } for (let i of this.allChordCharacteristics.trainerChordInversions) { this.selectedChordInversions.set(i, false); } } onChordQualitySelected(quality: string) { //Setting or unsetting a chord quality in the selected characteristics. let isSet = this.selectedChordQualities.get(quality); if (isSet === undefined) { // If it can't find the value, then there is a bug. window.alert("Cannot select chord quality"); return; } else { this.selectedChordQualities.set(quality, !isSet); } } onChordInversionSelected(inversion: string) { //Setting or unsetting a chord inversion in the selected characteristics. let isSet = this.selectedChordInversions.get(inversion); if (isSet === undefined) { // If it can't find the value, then there is a bug. window.alert("Cannot select chord inversion");
this.selectedChordInversions.set(inversion, !isSet); } } onStartTrainerButtonSelected() { // Building an array of selected chord qualities. If none were selected, // then all are available to be tested on and they are added to the array. let chordQualities: string[] = [ ]; this.selectedChordQualities.forEach(function(value, key, map){ if (value === true) { chordQualities.push(key); } }); if (chordQualities.length === 0) { chordQualities = this.allChordCharacteristics.trainerChordQualities; } // Building an array of selected chord inversions. If none were selected, // then all are available to be tested on and they are added to the array. let chordInversions: string[] = [ ]; this.selectedChordInversions.forEach(function(value, key, map){ if (value === true) { chordInversions.push(key); } }); if (chordInversions.length === 0) { chordInversions = this.allChordCharacteristics.trainerChordInversions; } let chordCharacteristics: ChordCharacteristics = new ChordCharacteristics(chordQualities, chordInversions); this.router.navigate(['/chordTester', chordCharacteristics]); } }
return; } else {
random_line_split
custom-mode-characteristics.component.ts
import { Component } from '@angular/core'; import { CustomModeCharacteristicsService } from './custom-mode-characteristics.service'; import { ChordCharacteristics } from './chord-characteristics'; import { Router } from '@angular/router'; @Component({ selector: 'custom-mode-characteristics', templateUrl: 'app/custom-mode-characteristics.html', styleUrls: ['app/custom-mode-characteristics.css'], providers: [CustomModeCharacteristicsService] }) // The view for selecting chord characteristics that will be tested in custom // mode. export class CustomModeCharacteristics { private selectedChordQualities: Map<string, boolean> = new Map<string, boolean>(); private selectedChordInversions: Map<string, boolean> = new Map<string, boolean>(); private allChordCharacteristics: ChordCharacteristics = new ChordCharacteristics();
(private customModeCharacteristicsService: CustomModeCharacteristicsService, private router : Router) {} ngOnInit() { this.customModeCharacteristicsService.getCustomModeChordCharacteristics() .then(characteristics => this.initializeChordCharacteristics(characteristics)) .catch(error => window.alert(error._body)); } // Initializes the chord characteristics data structures in this class after // they are received from the server. private initializeChordCharacteristics(chordCharacteristics : ChordCharacteristics) { this.allChordCharacteristics = chordCharacteristics; // Adding all chord characteristics to the specific maps of selected // characteristics. this.selectedChordQualities = new Map<string, boolean>(); this.selectedChordInversions = new Map<string, boolean>(); for (let q of this.allChordCharacteristics.trainerChordQualities) { this.selectedChordQualities.set(q, false); } for (let i of this.allChordCharacteristics.trainerChordInversions) { this.selectedChordInversions.set(i, false); } } onChordQualitySelected(quality: string) { //Setting or unsetting a chord quality in the selected characteristics. let isSet = this.selectedChordQualities.get(quality); if (isSet === undefined) { // If it can't find the value, then there is a bug. window.alert("Cannot select chord quality"); return; } else { this.selectedChordQualities.set(quality, !isSet); } } onChordInversionSelected(inversion: string) { //Setting or unsetting a chord inversion in the selected characteristics. let isSet = this.selectedChordInversions.get(inversion); if (isSet === undefined) { // If it can't find the value, then there is a bug. window.alert("Cannot select chord inversion"); return; } else { this.selectedChordInversions.set(inversion, !isSet); } } onStartTrainerButtonSelected() { // Building an array of selected chord qualities. If none were selected, // then all are available to be tested on and they are added to the array. let chordQualities: string[] = [ ]; this.selectedChordQualities.forEach(function(value, key, map){ if (value === true) { chordQualities.push(key); } }); if (chordQualities.length === 0) { chordQualities = this.allChordCharacteristics.trainerChordQualities; } // Building an array of selected chord inversions. If none were selected, // then all are available to be tested on and they are added to the array. let chordInversions: string[] = [ ]; this.selectedChordInversions.forEach(function(value, key, map){ if (value === true) { chordInversions.push(key); } }); if (chordInversions.length === 0) { chordInversions = this.allChordCharacteristics.trainerChordInversions; } let chordCharacteristics: ChordCharacteristics = new ChordCharacteristics(chordQualities, chordInversions); this.router.navigate(['/chordTester', chordCharacteristics]); } }
constructor
identifier_name
custom-mode-characteristics.component.ts
import { Component } from '@angular/core'; import { CustomModeCharacteristicsService } from './custom-mode-characteristics.service'; import { ChordCharacteristics } from './chord-characteristics'; import { Router } from '@angular/router'; @Component({ selector: 'custom-mode-characteristics', templateUrl: 'app/custom-mode-characteristics.html', styleUrls: ['app/custom-mode-characteristics.css'], providers: [CustomModeCharacteristicsService] }) // The view for selecting chord characteristics that will be tested in custom // mode. export class CustomModeCharacteristics { private selectedChordQualities: Map<string, boolean> = new Map<string, boolean>(); private selectedChordInversions: Map<string, boolean> = new Map<string, boolean>(); private allChordCharacteristics: ChordCharacteristics = new ChordCharacteristics(); constructor(private customModeCharacteristicsService: CustomModeCharacteristicsService, private router : Router) {} ngOnInit() { this.customModeCharacteristicsService.getCustomModeChordCharacteristics() .then(characteristics => this.initializeChordCharacteristics(characteristics)) .catch(error => window.alert(error._body)); } // Initializes the chord characteristics data structures in this class after // they are received from the server. private initializeChordCharacteristics(chordCharacteristics : ChordCharacteristics) { this.allChordCharacteristics = chordCharacteristics; // Adding all chord characteristics to the specific maps of selected // characteristics. this.selectedChordQualities = new Map<string, boolean>(); this.selectedChordInversions = new Map<string, boolean>(); for (let q of this.allChordCharacteristics.trainerChordQualities) { this.selectedChordQualities.set(q, false); } for (let i of this.allChordCharacteristics.trainerChordInversions) { this.selectedChordInversions.set(i, false); } } onChordQualitySelected(quality: string)
onChordInversionSelected(inversion: string) { //Setting or unsetting a chord inversion in the selected characteristics. let isSet = this.selectedChordInversions.get(inversion); if (isSet === undefined) { // If it can't find the value, then there is a bug. window.alert("Cannot select chord inversion"); return; } else { this.selectedChordInversions.set(inversion, !isSet); } } onStartTrainerButtonSelected() { // Building an array of selected chord qualities. If none were selected, // then all are available to be tested on and they are added to the array. let chordQualities: string[] = [ ]; this.selectedChordQualities.forEach(function(value, key, map){ if (value === true) { chordQualities.push(key); } }); if (chordQualities.length === 0) { chordQualities = this.allChordCharacteristics.trainerChordQualities; } // Building an array of selected chord inversions. If none were selected, // then all are available to be tested on and they are added to the array. let chordInversions: string[] = [ ]; this.selectedChordInversions.forEach(function(value, key, map){ if (value === true) { chordInversions.push(key); } }); if (chordInversions.length === 0) { chordInversions = this.allChordCharacteristics.trainerChordInversions; } let chordCharacteristics: ChordCharacteristics = new ChordCharacteristics(chordQualities, chordInversions); this.router.navigate(['/chordTester', chordCharacteristics]); } }
{ //Setting or unsetting a chord quality in the selected characteristics. let isSet = this.selectedChordQualities.get(quality); if (isSet === undefined) { // If it can't find the value, then there is a bug. window.alert("Cannot select chord quality"); return; } else { this.selectedChordQualities.set(quality, !isSet); } }
identifier_body
metrics.rs
use std::fmt; use std::time::Duration; use tic::Receiver; #[derive(Clone, PartialEq, Eq, Hash, Debug)] pub enum Metric { Request, Processed, } impl fmt::Display for Metric { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
} pub fn init(listen: Option<String>) -> Receiver<Metric> { let mut config = Receiver::<Metric>::configure() .batch_size(1) .capacity(4096) .poll_delay(Some(Duration::new(0, 1_000_000))) .service(true); if let Some(addr) = listen { info!("listening STATS {}", addr); config = config.http_listen(addr); } config.build() }
{ match *self { Metric::Request => write!(f, "request"), Metric::Processed => write!(f, "processed"), } }
identifier_body
metrics.rs
use std::fmt; use std::time::Duration; use tic::Receiver; #[derive(Clone, PartialEq, Eq, Hash, Debug)] pub enum Metric { Request, Processed, } impl fmt::Display for Metric { fn
(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Metric::Request => write!(f, "request"), Metric::Processed => write!(f, "processed"), } } } pub fn init(listen: Option<String>) -> Receiver<Metric> { let mut config = Receiver::<Metric>::configure() .batch_size(1) .capacity(4096) .poll_delay(Some(Duration::new(0, 1_000_000))) .service(true); if let Some(addr) = listen { info!("listening STATS {}", addr); config = config.http_listen(addr); } config.build() }
fmt
identifier_name
metrics.rs
use std::fmt; use std::time::Duration; use tic::Receiver; #[derive(Clone, PartialEq, Eq, Hash, Debug)] pub enum Metric { Request, Processed, } impl fmt::Display for Metric { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self {
} } } pub fn init(listen: Option<String>) -> Receiver<Metric> { let mut config = Receiver::<Metric>::configure() .batch_size(1) .capacity(4096) .poll_delay(Some(Duration::new(0, 1_000_000))) .service(true); if let Some(addr) = listen { info!("listening STATS {}", addr); config = config.http_listen(addr); } config.build() }
Metric::Request => write!(f, "request"), Metric::Processed => write!(f, "processed"),
random_line_split
FormElements.story.tsx
/** * @author Stéphane LaFlèche <stephane.l@vanillaforums.com> * @copyright 2009-2019 Vanilla Forums Inc. * @license GPL-2.0-only */ import { StoryHeading } from "@library/storybook/StoryHeading"; import { storiesOf } from "@storybook/react"; import React, { CSSProperties } from "react"; import { StoryContent } from "@library/storybook/StoryContent"; import { StoryParagraph } from "@library/storybook/StoryParagraph"; import { t } from "@library/utility/appUtils"; import InputBlock from "@library/forms/InputBlock"; import InputTextBlock from "@library/forms/InputTextBlock"; import MultiUserInput from "@library/features/users/MultiUserInput"; import { IComboBoxOption } from "@library/features/search/SearchBar"; import Checkbox from "@library/forms/Checkbox"; import StoryExampleDropDownSearch from "@library/flyouts/StoryExampleDropDownSearch"; import { uniqueIDFromPrefix } from "@library/utility/idUtils"; import RadioButton from "@library/forms/RadioButton"; import "@library/forms/datePicker.scss"; import RadioButtonGroup from "@library/forms/RadioButtonGroup"; import CheckboxGroup from "@library/forms/CheckboxGroup"; import { StorySmallContent } from "@library/storybook/StorySmallContent"; import { FormToggle } from "@library/forms/FormToggle"; import { flexHelper } from "@library/styles/styleHelpers"; import { cssOut } from "@dashboard/compatibilityStyles/cssOut"; import { suggestedTextStyleHelper } from "@library/features/search/suggestedTextStyles"; import LazyDateRange from "@library/forms/LazyDateRange"; const story = storiesOf("Forms/User Facing", module); story.add("Elements", () => { let activeItem = "Tab A"; /** * Simple form setter. */ const handleUserChange = (options: IComboBoxOption[]) => { // Do something doNothing(); }; // To avoid clashing with other components also using these radio buttons, you need to generate a unique ID for the group. const radioButtonGroup1 = uniqueIDFromPrefix("radioButtonGroupA"); cssOut(`.suggestedTextInput-option`, suggestedTextStyleHelper().option); return ( <StoryContent> <StoryHeading depth={1}>Form Elements</StoryHeading> <StoryHeading>Checkbox</StoryHeading> <CheckboxGroup label={"Check Box States"}> <Checkbox label="Normal" /> <Checkbox label="Hover/Focus" fakeFocus /> <Checkbox label="Checked" defaultChecked /> <Checkbox label="Disabled" disabled /> <Checkbox label="Checked & Disabled" defaultChecked disabled /> </CheckboxGroup> <StoryHeading>Hidden Label</StoryHeading> <Checkbox label="Tooltip Label" tooltipLabel /> <StoryHeading>Checkboxes - In a Group</StoryHeading>
<Checkbox label="Option B" /> <Checkbox label="Option C" /> <Checkbox label="Option D" /> </CheckboxGroup> <StoryHeading>Toggles</StoryHeading> <div style={flexHelper().middle() as CSSProperties}> <StoryToggle accessibleLabel="Enabled" enabled={true} /> <StoryToggle accessibleLabel="Disabled" enabled={false} /> <StoryToggle accessibleLabel="Indeterminate" indeterminate enabled={true} /> <StoryToggle accessibleLabel="Indeterminate" indeterminate enabled={false} /> </div> <StoryHeading>Toggles (Slim)</StoryHeading> <div style={flexHelper().middle() as CSSProperties}> <StoryToggle accessibleLabel="Enabled" enabled={true} slim /> <StoryToggle accessibleLabel="Disabled" enabled={false} slim /> <StoryToggle accessibleLabel="Indeterminate" indeterminate enabled={true} slim /> <StoryToggle accessibleLabel="Indeterminate" indeterminate enabled={false} slim /> </div> <StoryHeading>Radio Buttons - In a Group</StoryHeading> <RadioButtonGroup label={"Gaggle of radio buttons"}> <RadioButton label={"Option A"} name={radioButtonGroup1} defaultChecked /> <RadioButton label={"Option B"} name={radioButtonGroup1} /> <RadioButton label={"Option C (hovered)"} name={radioButtonGroup1} fakeFocus /> <RadioButton label={"Option D"} name={radioButtonGroup1} /> <RadioButton label={"Option E"} name={radioButtonGroup1} /> </RadioButtonGroup> <StoryHeading>InputBlock</StoryHeading> <StoryParagraph>Helper component to add label to various inputs</StoryParagraph> <StoryHeading>Example of label that can be used for any input</StoryHeading> <InputBlock label={"My Label"}> <div>{"[Some Input]"}</div> </InputBlock> <StoryHeading>Input Text Block</StoryHeading> <InputTextBlock label={t("Text Input")} inputProps={{ value: "Some Text!" }} /> <StoryHeading>Input Text (password type)</StoryHeading> <StoryParagraph>You can set the `type` of the text input to any standard HTML5 values.</StoryParagraph> <InputTextBlock label={t("Password")} type={"password"} inputProps={{ type: "password" }} /> <StoryHeading>Radio Buttons styled as tabs</StoryHeading> <StoryParagraph> The state for this component needs to be managed by the parent. (Will not update here when you click) </StoryParagraph> <StoryHeading>Tokens Input</StoryHeading> <MultiUserInput onChange={handleUserChange} value={[ { value: "Astérix", label: "Astérix", }, { value: "Obélix", label: "Obélix", }, { value: "Idéfix", label: "Idéfix", }, { value: "Panoramix", label: "Panoramix", }, ]} /> <StoryHeading>Dropdown with search</StoryHeading> <StoryExampleDropDownSearch /> <StoryHeading>Date Range</StoryHeading> <StorySmallContent> <LazyDateRange onStartChange={doNothing} onEndChange={doNothing} start={undefined} end={undefined} /> </StorySmallContent> </StoryContent> ); }); const doNothing = () => { return; }; function StoryToggle(props: Omit<React.ComponentProps<typeof FormToggle>, "onChange">) { return ( <InputBlock label={props.accessibleLabel}> <FormToggle {...props} enabled={false} onChange={doNothing} /> </InputBlock> ); }
<CheckboxGroup label={"A sleuth of check boxes"}> <Checkbox label="Option A" />
random_line_split
FormElements.story.tsx
/** * @author Stéphane LaFlèche <stephane.l@vanillaforums.com> * @copyright 2009-2019 Vanilla Forums Inc. * @license GPL-2.0-only */ import { StoryHeading } from "@library/storybook/StoryHeading"; import { storiesOf } from "@storybook/react"; import React, { CSSProperties } from "react"; import { StoryContent } from "@library/storybook/StoryContent"; import { StoryParagraph } from "@library/storybook/StoryParagraph"; import { t } from "@library/utility/appUtils"; import InputBlock from "@library/forms/InputBlock"; import InputTextBlock from "@library/forms/InputTextBlock"; import MultiUserInput from "@library/features/users/MultiUserInput"; import { IComboBoxOption } from "@library/features/search/SearchBar"; import Checkbox from "@library/forms/Checkbox"; import StoryExampleDropDownSearch from "@library/flyouts/StoryExampleDropDownSearch"; import { uniqueIDFromPrefix } from "@library/utility/idUtils"; import RadioButton from "@library/forms/RadioButton"; import "@library/forms/datePicker.scss"; import RadioButtonGroup from "@library/forms/RadioButtonGroup"; import CheckboxGroup from "@library/forms/CheckboxGroup"; import { StorySmallContent } from "@library/storybook/StorySmallContent"; import { FormToggle } from "@library/forms/FormToggle"; import { flexHelper } from "@library/styles/styleHelpers"; import { cssOut } from "@dashboard/compatibilityStyles/cssOut"; import { suggestedTextStyleHelper } from "@library/features/search/suggestedTextStyles"; import LazyDateRange from "@library/forms/LazyDateRange"; const story = storiesOf("Forms/User Facing", module); story.add("Elements", () => { let activeItem = "Tab A"; /** * Simple form setter. */ const handleUserChange = (options: IComboBoxOption[]) => { // Do something doNothing(); }; // To avoid clashing with other components also using these radio buttons, you need to generate a unique ID for the group. const radioButtonGroup1 = uniqueIDFromPrefix("radioButtonGroupA"); cssOut(`.suggestedTextInput-option`, suggestedTextStyleHelper().option); return ( <StoryContent> <StoryHeading depth={1}>Form Elements</StoryHeading> <StoryHeading>Checkbox</StoryHeading> <CheckboxGroup label={"Check Box States"}> <Checkbox label="Normal" /> <Checkbox label="Hover/Focus" fakeFocus /> <Checkbox label="Checked" defaultChecked /> <Checkbox label="Disabled" disabled /> <Checkbox label="Checked & Disabled" defaultChecked disabled /> </CheckboxGroup> <StoryHeading>Hidden Label</StoryHeading> <Checkbox label="Tooltip Label" tooltipLabel /> <StoryHeading>Checkboxes - In a Group</StoryHeading> <CheckboxGroup label={"A sleuth of check boxes"}> <Checkbox label="Option A" /> <Checkbox label="Option B" /> <Checkbox label="Option C" /> <Checkbox label="Option D" /> </CheckboxGroup> <StoryHeading>Toggles</StoryHeading> <div style={flexHelper().middle() as CSSProperties}> <StoryToggle accessibleLabel="Enabled" enabled={true} /> <StoryToggle accessibleLabel="Disabled" enabled={false} /> <StoryToggle accessibleLabel="Indeterminate" indeterminate enabled={true} /> <StoryToggle accessibleLabel="Indeterminate" indeterminate enabled={false} /> </div> <StoryHeading>Toggles (Slim)</StoryHeading> <div style={flexHelper().middle() as CSSProperties}> <StoryToggle accessibleLabel="Enabled" enabled={true} slim /> <StoryToggle accessibleLabel="Disabled" enabled={false} slim /> <StoryToggle accessibleLabel="Indeterminate" indeterminate enabled={true} slim /> <StoryToggle accessibleLabel="Indeterminate" indeterminate enabled={false} slim /> </div> <StoryHeading>Radio Buttons - In a Group</StoryHeading> <RadioButtonGroup label={"Gaggle of radio buttons"}> <RadioButton label={"Option A"} name={radioButtonGroup1} defaultChecked /> <RadioButton label={"Option B"} name={radioButtonGroup1} /> <RadioButton label={"Option C (hovered)"} name={radioButtonGroup1} fakeFocus /> <RadioButton label={"Option D"} name={radioButtonGroup1} /> <RadioButton label={"Option E"} name={radioButtonGroup1} /> </RadioButtonGroup> <StoryHeading>InputBlock</StoryHeading> <StoryParagraph>Helper component to add label to various inputs</StoryParagraph> <StoryHeading>Example of label that can be used for any input</StoryHeading> <InputBlock label={"My Label"}> <div>{"[Some Input]"}</div> </InputBlock> <StoryHeading>Input Text Block</StoryHeading> <InputTextBlock label={t("Text Input")} inputProps={{ value: "Some Text!" }} /> <StoryHeading>Input Text (password type)</StoryHeading> <StoryParagraph>You can set the `type` of the text input to any standard HTML5 values.</StoryParagraph> <InputTextBlock label={t("Password")} type={"password"} inputProps={{ type: "password" }} /> <StoryHeading>Radio Buttons styled as tabs</StoryHeading> <StoryParagraph> The state for this component needs to be managed by the parent. (Will not update here when you click) </StoryParagraph> <StoryHeading>Tokens Input</StoryHeading> <MultiUserInput onChange={handleUserChange} value={[ { value: "Astérix", label: "Astérix", }, { value: "Obélix", label: "Obélix", }, { value: "Idéfix", label: "Idéfix", }, { value: "Panoramix", label: "Panoramix", }, ]} /> <StoryHeading>Dropdown with search</StoryHeading> <StoryExampleDropDownSearch /> <StoryHeading>Date Range</StoryHeading> <StorySmallContent> <LazyDateRange onStartChange={doNothing} onEndChange={doNothing} start={undefined} end={undefined} /> </StorySmallContent> </StoryContent> ); }); const doNothing = () => { return; }; function StoryTog
Omit<React.ComponentProps<typeof FormToggle>, "onChange">) { return ( <InputBlock label={props.accessibleLabel}> <FormToggle {...props} enabled={false} onChange={doNothing} /> </InputBlock> ); }
gle(props:
identifier_name
FormElements.story.tsx
/** * @author Stéphane LaFlèche <stephane.l@vanillaforums.com> * @copyright 2009-2019 Vanilla Forums Inc. * @license GPL-2.0-only */ import { StoryHeading } from "@library/storybook/StoryHeading"; import { storiesOf } from "@storybook/react"; import React, { CSSProperties } from "react"; import { StoryContent } from "@library/storybook/StoryContent"; import { StoryParagraph } from "@library/storybook/StoryParagraph"; import { t } from "@library/utility/appUtils"; import InputBlock from "@library/forms/InputBlock"; import InputTextBlock from "@library/forms/InputTextBlock"; import MultiUserInput from "@library/features/users/MultiUserInput"; import { IComboBoxOption } from "@library/features/search/SearchBar"; import Checkbox from "@library/forms/Checkbox"; import StoryExampleDropDownSearch from "@library/flyouts/StoryExampleDropDownSearch"; import { uniqueIDFromPrefix } from "@library/utility/idUtils"; import RadioButton from "@library/forms/RadioButton"; import "@library/forms/datePicker.scss"; import RadioButtonGroup from "@library/forms/RadioButtonGroup"; import CheckboxGroup from "@library/forms/CheckboxGroup"; import { StorySmallContent } from "@library/storybook/StorySmallContent"; import { FormToggle } from "@library/forms/FormToggle"; import { flexHelper } from "@library/styles/styleHelpers"; import { cssOut } from "@dashboard/compatibilityStyles/cssOut"; import { suggestedTextStyleHelper } from "@library/features/search/suggestedTextStyles"; import LazyDateRange from "@library/forms/LazyDateRange"; const story = storiesOf("Forms/User Facing", module); story.add("Elements", () => { let activeItem = "Tab A"; /** * Simple form setter. */ const handleUserChange = (options: IComboBoxOption[]) => { // Do something doNothing(); }; // To avoid clashing with other components also using these radio buttons, you need to generate a unique ID for the group. const radioButtonGroup1 = uniqueIDFromPrefix("radioButtonGroupA"); cssOut(`.suggestedTextInput-option`, suggestedTextStyleHelper().option); return ( <StoryContent> <StoryHeading depth={1}>Form Elements</StoryHeading> <StoryHeading>Checkbox</StoryHeading> <CheckboxGroup label={"Check Box States"}> <Checkbox label="Normal" /> <Checkbox label="Hover/Focus" fakeFocus /> <Checkbox label="Checked" defaultChecked /> <Checkbox label="Disabled" disabled /> <Checkbox label="Checked & Disabled" defaultChecked disabled /> </CheckboxGroup> <StoryHeading>Hidden Label</StoryHeading> <Checkbox label="Tooltip Label" tooltipLabel /> <StoryHeading>Checkboxes - In a Group</StoryHeading> <CheckboxGroup label={"A sleuth of check boxes"}> <Checkbox label="Option A" /> <Checkbox label="Option B" /> <Checkbox label="Option C" /> <Checkbox label="Option D" /> </CheckboxGroup> <StoryHeading>Toggles</StoryHeading> <div style={flexHelper().middle() as CSSProperties}> <StoryToggle accessibleLabel="Enabled" enabled={true} /> <StoryToggle accessibleLabel="Disabled" enabled={false} /> <StoryToggle accessibleLabel="Indeterminate" indeterminate enabled={true} /> <StoryToggle accessibleLabel="Indeterminate" indeterminate enabled={false} /> </div> <StoryHeading>Toggles (Slim)</StoryHeading> <div style={flexHelper().middle() as CSSProperties}> <StoryToggle accessibleLabel="Enabled" enabled={true} slim /> <StoryToggle accessibleLabel="Disabled" enabled={false} slim /> <StoryToggle accessibleLabel="Indeterminate" indeterminate enabled={true} slim /> <StoryToggle accessibleLabel="Indeterminate" indeterminate enabled={false} slim /> </div> <StoryHeading>Radio Buttons - In a Group</StoryHeading> <RadioButtonGroup label={"Gaggle of radio buttons"}> <RadioButton label={"Option A"} name={radioButtonGroup1} defaultChecked /> <RadioButton label={"Option B"} name={radioButtonGroup1} /> <RadioButton label={"Option C (hovered)"} name={radioButtonGroup1} fakeFocus /> <RadioButton label={"Option D"} name={radioButtonGroup1} /> <RadioButton label={"Option E"} name={radioButtonGroup1} /> </RadioButtonGroup> <StoryHeading>InputBlock</StoryHeading> <StoryParagraph>Helper component to add label to various inputs</StoryParagraph> <StoryHeading>Example of label that can be used for any input</StoryHeading> <InputBlock label={"My Label"}> <div>{"[Some Input]"}</div> </InputBlock> <StoryHeading>Input Text Block</StoryHeading> <InputTextBlock label={t("Text Input")} inputProps={{ value: "Some Text!" }} /> <StoryHeading>Input Text (password type)</StoryHeading> <StoryParagraph>You can set the `type` of the text input to any standard HTML5 values.</StoryParagraph> <InputTextBlock label={t("Password")} type={"password"} inputProps={{ type: "password" }} /> <StoryHeading>Radio Buttons styled as tabs</StoryHeading> <StoryParagraph> The state for this component needs to be managed by the parent. (Will not update here when you click) </StoryParagraph> <StoryHeading>Tokens Input</StoryHeading> <MultiUserInput onChange={handleUserChange} value={[ { value: "Astérix", label: "Astérix", }, { value: "Obélix", label: "Obélix", }, { value: "Idéfix", label: "Idéfix", }, { value: "Panoramix", label: "Panoramix", }, ]} /> <StoryHeading>Dropdown with search</StoryHeading> <StoryExampleDropDownSearch /> <StoryHeading>Date Range</StoryHeading> <StorySmallContent> <LazyDateRange onStartChange={doNothing} onEndChange={doNothing} start={undefined} end={undefined} /> </StorySmallContent> </StoryContent> ); }); const doNothing = () => { return; }; function StoryToggle(props: Omit<React.ComponentProps<typeof FormToggle>, "onChange">) { re
turn ( <InputBlock label={props.accessibleLabel}> <FormToggle {...props} enabled={false} onChange={doNothing} /> </InputBlock> ); }
identifier_body
permissionstatus.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::PermissionStatusBinding::{self, PermissionDescriptor, PermissionName}; use dom::bindings::codegen::Bindings::PermissionStatusBinding::PermissionState; use dom::bindings::codegen::Bindings::PermissionStatusBinding::PermissionStatusMethods; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::root::DomRoot; use dom::eventtarget::EventTarget; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use std::cell::Cell; use std::fmt::{self, Display, Formatter}; // https://w3c.github.io/permissions/#permissionstatus #[dom_struct] pub struct PermissionStatus { eventtarget: EventTarget, state: Cell<PermissionState>, query: Cell<PermissionName>, } impl PermissionStatus { pub fn new_inherited(query: PermissionName) -> PermissionStatus { PermissionStatus { eventtarget: EventTarget::new_inherited(), state: Cell::new(PermissionState::Denied), query: Cell::new(query), } } pub fn new(global: &GlobalScope, query: &PermissionDescriptor) -> DomRoot<PermissionStatus> { reflect_dom_object(Box::new(PermissionStatus::new_inherited(query.name)), global, PermissionStatusBinding::Wrap) } pub fn set_state(&self, state: PermissionState) { self.state.set(state); } pub fn get_query(&self) -> PermissionName { self.query.get() } } impl PermissionStatusMethods for PermissionStatus { // https://w3c.github.io/permissions/#dom-permissionstatus-state fn State(&self) -> PermissionState { self.state.get() } // https://w3c.github.io/permissions/#dom-permissionstatus-onchange event_handler!(onchange, GetOnchange, SetOnchange);
impl Display for PermissionName { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "{}", self.as_str()) } }
}
random_line_split
permissionstatus.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::PermissionStatusBinding::{self, PermissionDescriptor, PermissionName}; use dom::bindings::codegen::Bindings::PermissionStatusBinding::PermissionState; use dom::bindings::codegen::Bindings::PermissionStatusBinding::PermissionStatusMethods; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::root::DomRoot; use dom::eventtarget::EventTarget; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use std::cell::Cell; use std::fmt::{self, Display, Formatter}; // https://w3c.github.io/permissions/#permissionstatus #[dom_struct] pub struct PermissionStatus { eventtarget: EventTarget, state: Cell<PermissionState>, query: Cell<PermissionName>, } impl PermissionStatus { pub fn new_inherited(query: PermissionName) -> PermissionStatus { PermissionStatus { eventtarget: EventTarget::new_inherited(), state: Cell::new(PermissionState::Denied), query: Cell::new(query), } } pub fn new(global: &GlobalScope, query: &PermissionDescriptor) -> DomRoot<PermissionStatus> { reflect_dom_object(Box::new(PermissionStatus::new_inherited(query.name)), global, PermissionStatusBinding::Wrap) } pub fn set_state(&self, state: PermissionState) { self.state.set(state); } pub fn get_query(&self) -> PermissionName { self.query.get() } } impl PermissionStatusMethods for PermissionStatus { // https://w3c.github.io/permissions/#dom-permissionstatus-state fn State(&self) -> PermissionState { self.state.get() } // https://w3c.github.io/permissions/#dom-permissionstatus-onchange event_handler!(onchange, GetOnchange, SetOnchange); } impl Display for PermissionName { fn fmt(&self, f: &mut Formatter) -> fmt::Result
}
{ write!(f, "{}", self.as_str()) }
identifier_body
permissionstatus.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::PermissionStatusBinding::{self, PermissionDescriptor, PermissionName}; use dom::bindings::codegen::Bindings::PermissionStatusBinding::PermissionState; use dom::bindings::codegen::Bindings::PermissionStatusBinding::PermissionStatusMethods; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::root::DomRoot; use dom::eventtarget::EventTarget; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use std::cell::Cell; use std::fmt::{self, Display, Formatter}; // https://w3c.github.io/permissions/#permissionstatus #[dom_struct] pub struct PermissionStatus { eventtarget: EventTarget, state: Cell<PermissionState>, query: Cell<PermissionName>, } impl PermissionStatus { pub fn new_inherited(query: PermissionName) -> PermissionStatus { PermissionStatus { eventtarget: EventTarget::new_inherited(), state: Cell::new(PermissionState::Denied), query: Cell::new(query), } } pub fn
(global: &GlobalScope, query: &PermissionDescriptor) -> DomRoot<PermissionStatus> { reflect_dom_object(Box::new(PermissionStatus::new_inherited(query.name)), global, PermissionStatusBinding::Wrap) } pub fn set_state(&self, state: PermissionState) { self.state.set(state); } pub fn get_query(&self) -> PermissionName { self.query.get() } } impl PermissionStatusMethods for PermissionStatus { // https://w3c.github.io/permissions/#dom-permissionstatus-state fn State(&self) -> PermissionState { self.state.get() } // https://w3c.github.io/permissions/#dom-permissionstatus-onchange event_handler!(onchange, GetOnchange, SetOnchange); } impl Display for PermissionName { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "{}", self.as_str()) } }
new
identifier_name
polylinize.py
#!/usr/bin/env python # Convert line elements with overlapping endpoints into polylines in an # SVG file. import os import sys try: from lxml import etree except ImportError: import xml.etree.ElementTree as etree from collections import defaultdict from optparse import OptionParser SVG_NS = 'http://www.w3.org/2000/svg' START = 1 END = 2 class Line(object): def __init__(self, line_element): a = line_element.attrib self.x1 = float(a['x1']) self.y1 = float(a['y1']) self.x2 = float(a['x2']) self.y2 = float(a['y2']) self.strokeWidth = float(a['stroke-width']) def reverse(self): self.x1, self.x2 = self.x2, self.x1 self.y1, self.y2 = self.y2, self.y1 def start_hash(self): return str(self.x1) + ',' + str(self.y1) def end_hash(self): return str(self.x2) + ',' + str(self.y2) def endpoint(self, direction): if direction == START: return self.start_hash() else: return self.end_hash() def get_other_hash(self, key): h = self.start_hash() if h == key: h = self.end_hash() return h def __repr__(self): return '((%s,%s),(%s,%s),sw:%s)' % (self.x1, self.y1, self.x2, self.y2, self.strokeWidth) class EndpointHash(object): def __init__(self, lines): self.endpoints = defaultdict(list) for l in lines: self.endpoints[l.start_hash()].append(l) self.endpoints[l.end_hash()].append(l) def count_overlapping_points(self): count = 0 for key, lines in self.endpoints.iteritems(): l = len(lines) if l > 1: count += 1 return count def _del_line(self, key, line): self.endpoints[key].remove(line) if len(self.endpoints[key]) == 0: del self.endpoints[key] def remove_line(self, line): key = line.start_hash() self._del_line(key, line) self._del_line(line.get_other_hash(key), line) def pop_connected_line(self, line, key): if key in self.endpoints: line = self.endpoints[key][0] self.remove_line(line) return line else: return def parse_svg(fname): print "Parsing '%s'..." % (fname) return etree.parse(fname) def get_lines(svg): lines = [] for l in svg.getroot().iter('{%s}line' % SVG_NS): lines.append(Line(l)) return lines def align_lines(l1, l2): if ( l1.x1 == l2.x1 and l1.y1 == l2.y1 or l1.x2 == l2.x2 and l1.y2 == l2.y2): l2.reverse() def connect_lines(lines, endpoint_hash, line, direction, poly): while True: key = line.endpoint(direction) connected_line = endpoint_hash.pop_connected_line(line, key) if connected_line: if direction == START:
else: poly.append(connected_line) align_lines(line, connected_line) lines.remove(connected_line) line = connected_line else: break def find_polylines(lines, endpoint_hash): polylines = [] while lines: line = lines.pop() endpoint_hash.remove_line(line) poly = [line] connect_lines(lines, endpoint_hash, line, START, poly) connect_lines(lines, endpoint_hash, line, END, poly) polylines.append(poly) return polylines def optimize(svg): lines = get_lines(svg) print '%s line segments found' % len(lines) lines_by_width = defaultdict(list) for l in lines: lines_by_width[l.strokeWidth].append(l) del lines print '%s different stroke widths found:' % len(lines_by_width) for width, lines in lines_by_width.iteritems(): print ' strokeWidth: %s (%s lines)' % (width, len(lines)) polylines = [] for width, lines in lines_by_width.iteritems(): print 'Finding polylines (strokeWidth: %s)... ' % width endpoint_hash = EndpointHash(lines) overlapping_points = endpoint_hash.count_overlapping_points() print (' %s line segments, %s overlapping points' % (len(lines), overlapping_points)), p = find_polylines(lines, endpoint_hash) print '-> %s polylines' % len(p) polylines += p return polylines def write_svg(polylines, outfile): print "Writing '%s'..." % outfile f = open(outfile, 'w') f.write("""<?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg" version="1.1"> """) def point_to_str(x, y): return '%s,%s ' % (x, y) for p in polylines: points = [] for line in p: if not points: points.append(point_to_str(line.x1, line.y1)) points.append(point_to_str(line.x2, line.y2)) f.write('<polyline fill="none" stroke="#000" stroke-width="%s" points="%s"/>\n' % (p[0].strokeWidth, ' '.join(points))) f.write('</svg>\n') f.close() def get_filesize(fname): return os.stat(fname).st_size def print_size_stats(infile, outfile): insize = get_filesize(infile) outsize = get_filesize(outfile) print ('Original file size: %.2fKiB, new file size: %.2fKiB (%.2f)' % (insize / 1024., outsize / 1024., float(outsize) / insize * 100)) def main(): usage = 'Usage: %prog INFILE OUTFILE' parser = OptionParser(usage=usage) options, args = parser.parse_args() if len(args) < 2: parser.error('input and output files must be specified') return 2 infile = args[0] outfile = args[1] svg = parse_svg(infile) polylines = optimize(svg) print '%s polyline(s) found in total' % len(polylines) write_svg(polylines, outfile) print_size_stats(infile, outfile) return 0 if __name__ == '__main__': try: sys.exit(main()) except KeyboardInterrupt: sys.exit(1)
poly.insert(0, connected_line)
conditional_block
polylinize.py
#!/usr/bin/env python # Convert line elements with overlapping endpoints into polylines in an # SVG file. import os import sys try: from lxml import etree except ImportError: import xml.etree.ElementTree as etree from collections import defaultdict from optparse import OptionParser SVG_NS = 'http://www.w3.org/2000/svg' START = 1 END = 2 class Line(object): def __init__(self, line_element): a = line_element.attrib self.x1 = float(a['x1']) self.y1 = float(a['y1']) self.x2 = float(a['x2']) self.y2 = float(a['y2']) self.strokeWidth = float(a['stroke-width']) def reverse(self): self.x1, self.x2 = self.x2, self.x1 self.y1, self.y2 = self.y2, self.y1 def start_hash(self): return str(self.x1) + ',' + str(self.y1) def end_hash(self): return str(self.x2) + ',' + str(self.y2) def endpoint(self, direction): if direction == START: return self.start_hash() else: return self.end_hash() def get_other_hash(self, key): h = self.start_hash() if h == key: h = self.end_hash() return h def __repr__(self): return '((%s,%s),(%s,%s),sw:%s)' % (self.x1, self.y1, self.x2, self.y2, self.strokeWidth) class EndpointHash(object): def __init__(self, lines): self.endpoints = defaultdict(list) for l in lines: self.endpoints[l.start_hash()].append(l) self.endpoints[l.end_hash()].append(l) def count_overlapping_points(self): count = 0 for key, lines in self.endpoints.iteritems(): l = len(lines) if l > 1: count += 1 return count def _del_line(self, key, line): self.endpoints[key].remove(line) if len(self.endpoints[key]) == 0: del self.endpoints[key] def remove_line(self, line): key = line.start_hash() self._del_line(key, line) self._del_line(line.get_other_hash(key), line) def pop_connected_line(self, line, key): if key in self.endpoints: line = self.endpoints[key][0] self.remove_line(line) return line else: return def parse_svg(fname): print "Parsing '%s'..." % (fname) return etree.parse(fname) def get_lines(svg): lines = [] for l in svg.getroot().iter('{%s}line' % SVG_NS): lines.append(Line(l)) return lines def align_lines(l1, l2): if ( l1.x1 == l2.x1 and l1.y1 == l2.y1 or l1.x2 == l2.x2 and l1.y2 == l2.y2): l2.reverse() def connect_lines(lines, endpoint_hash, line, direction, poly): while True: key = line.endpoint(direction) connected_line = endpoint_hash.pop_connected_line(line, key) if connected_line: if direction == START: poly.insert(0, connected_line) else: poly.append(connected_line) align_lines(line, connected_line) lines.remove(connected_line) line = connected_line else: break def find_polylines(lines, endpoint_hash): polylines = [] while lines: line = lines.pop() endpoint_hash.remove_line(line) poly = [line] connect_lines(lines, endpoint_hash, line, START, poly) connect_lines(lines, endpoint_hash, line, END, poly) polylines.append(poly) return polylines def
(svg): lines = get_lines(svg) print '%s line segments found' % len(lines) lines_by_width = defaultdict(list) for l in lines: lines_by_width[l.strokeWidth].append(l) del lines print '%s different stroke widths found:' % len(lines_by_width) for width, lines in lines_by_width.iteritems(): print ' strokeWidth: %s (%s lines)' % (width, len(lines)) polylines = [] for width, lines in lines_by_width.iteritems(): print 'Finding polylines (strokeWidth: %s)... ' % width endpoint_hash = EndpointHash(lines) overlapping_points = endpoint_hash.count_overlapping_points() print (' %s line segments, %s overlapping points' % (len(lines), overlapping_points)), p = find_polylines(lines, endpoint_hash) print '-> %s polylines' % len(p) polylines += p return polylines def write_svg(polylines, outfile): print "Writing '%s'..." % outfile f = open(outfile, 'w') f.write("""<?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg" version="1.1"> """) def point_to_str(x, y): return '%s,%s ' % (x, y) for p in polylines: points = [] for line in p: if not points: points.append(point_to_str(line.x1, line.y1)) points.append(point_to_str(line.x2, line.y2)) f.write('<polyline fill="none" stroke="#000" stroke-width="%s" points="%s"/>\n' % (p[0].strokeWidth, ' '.join(points))) f.write('</svg>\n') f.close() def get_filesize(fname): return os.stat(fname).st_size def print_size_stats(infile, outfile): insize = get_filesize(infile) outsize = get_filesize(outfile) print ('Original file size: %.2fKiB, new file size: %.2fKiB (%.2f)' % (insize / 1024., outsize / 1024., float(outsize) / insize * 100)) def main(): usage = 'Usage: %prog INFILE OUTFILE' parser = OptionParser(usage=usage) options, args = parser.parse_args() if len(args) < 2: parser.error('input and output files must be specified') return 2 infile = args[0] outfile = args[1] svg = parse_svg(infile) polylines = optimize(svg) print '%s polyline(s) found in total' % len(polylines) write_svg(polylines, outfile) print_size_stats(infile, outfile) return 0 if __name__ == '__main__': try: sys.exit(main()) except KeyboardInterrupt: sys.exit(1)
optimize
identifier_name
polylinize.py
#!/usr/bin/env python # Convert line elements with overlapping endpoints into polylines in an # SVG file. import os import sys try: from lxml import etree except ImportError: import xml.etree.ElementTree as etree from collections import defaultdict from optparse import OptionParser SVG_NS = 'http://www.w3.org/2000/svg' START = 1 END = 2 class Line(object): def __init__(self, line_element): a = line_element.attrib self.x1 = float(a['x1']) self.y1 = float(a['y1']) self.x2 = float(a['x2']) self.y2 = float(a['y2']) self.strokeWidth = float(a['stroke-width']) def reverse(self): self.x1, self.x2 = self.x2, self.x1 self.y1, self.y2 = self.y2, self.y1 def start_hash(self): return str(self.x1) + ',' + str(self.y1) def end_hash(self): return str(self.x2) + ',' + str(self.y2) def endpoint(self, direction): if direction == START: return self.start_hash() else: return self.end_hash() def get_other_hash(self, key): h = self.start_hash() if h == key: h = self.end_hash() return h def __repr__(self): return '((%s,%s),(%s,%s),sw:%s)' % (self.x1, self.y1, self.x2, self.y2, self.strokeWidth) class EndpointHash(object): def __init__(self, lines): self.endpoints = defaultdict(list) for l in lines: self.endpoints[l.start_hash()].append(l) self.endpoints[l.end_hash()].append(l) def count_overlapping_points(self): count = 0
l = len(lines) if l > 1: count += 1 return count def _del_line(self, key, line): self.endpoints[key].remove(line) if len(self.endpoints[key]) == 0: del self.endpoints[key] def remove_line(self, line): key = line.start_hash() self._del_line(key, line) self._del_line(line.get_other_hash(key), line) def pop_connected_line(self, line, key): if key in self.endpoints: line = self.endpoints[key][0] self.remove_line(line) return line else: return def parse_svg(fname): print "Parsing '%s'..." % (fname) return etree.parse(fname) def get_lines(svg): lines = [] for l in svg.getroot().iter('{%s}line' % SVG_NS): lines.append(Line(l)) return lines def align_lines(l1, l2): if ( l1.x1 == l2.x1 and l1.y1 == l2.y1 or l1.x2 == l2.x2 and l1.y2 == l2.y2): l2.reverse() def connect_lines(lines, endpoint_hash, line, direction, poly): while True: key = line.endpoint(direction) connected_line = endpoint_hash.pop_connected_line(line, key) if connected_line: if direction == START: poly.insert(0, connected_line) else: poly.append(connected_line) align_lines(line, connected_line) lines.remove(connected_line) line = connected_line else: break def find_polylines(lines, endpoint_hash): polylines = [] while lines: line = lines.pop() endpoint_hash.remove_line(line) poly = [line] connect_lines(lines, endpoint_hash, line, START, poly) connect_lines(lines, endpoint_hash, line, END, poly) polylines.append(poly) return polylines def optimize(svg): lines = get_lines(svg) print '%s line segments found' % len(lines) lines_by_width = defaultdict(list) for l in lines: lines_by_width[l.strokeWidth].append(l) del lines print '%s different stroke widths found:' % len(lines_by_width) for width, lines in lines_by_width.iteritems(): print ' strokeWidth: %s (%s lines)' % (width, len(lines)) polylines = [] for width, lines in lines_by_width.iteritems(): print 'Finding polylines (strokeWidth: %s)... ' % width endpoint_hash = EndpointHash(lines) overlapping_points = endpoint_hash.count_overlapping_points() print (' %s line segments, %s overlapping points' % (len(lines), overlapping_points)), p = find_polylines(lines, endpoint_hash) print '-> %s polylines' % len(p) polylines += p return polylines def write_svg(polylines, outfile): print "Writing '%s'..." % outfile f = open(outfile, 'w') f.write("""<?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg" version="1.1"> """) def point_to_str(x, y): return '%s,%s ' % (x, y) for p in polylines: points = [] for line in p: if not points: points.append(point_to_str(line.x1, line.y1)) points.append(point_to_str(line.x2, line.y2)) f.write('<polyline fill="none" stroke="#000" stroke-width="%s" points="%s"/>\n' % (p[0].strokeWidth, ' '.join(points))) f.write('</svg>\n') f.close() def get_filesize(fname): return os.stat(fname).st_size def print_size_stats(infile, outfile): insize = get_filesize(infile) outsize = get_filesize(outfile) print ('Original file size: %.2fKiB, new file size: %.2fKiB (%.2f)' % (insize / 1024., outsize / 1024., float(outsize) / insize * 100)) def main(): usage = 'Usage: %prog INFILE OUTFILE' parser = OptionParser(usage=usage) options, args = parser.parse_args() if len(args) < 2: parser.error('input and output files must be specified') return 2 infile = args[0] outfile = args[1] svg = parse_svg(infile) polylines = optimize(svg) print '%s polyline(s) found in total' % len(polylines) write_svg(polylines, outfile) print_size_stats(infile, outfile) return 0 if __name__ == '__main__': try: sys.exit(main()) except KeyboardInterrupt: sys.exit(1)
for key, lines in self.endpoints.iteritems():
random_line_split
polylinize.py
#!/usr/bin/env python # Convert line elements with overlapping endpoints into polylines in an # SVG file. import os import sys try: from lxml import etree except ImportError: import xml.etree.ElementTree as etree from collections import defaultdict from optparse import OptionParser SVG_NS = 'http://www.w3.org/2000/svg' START = 1 END = 2 class Line(object): def __init__(self, line_element): a = line_element.attrib self.x1 = float(a['x1']) self.y1 = float(a['y1']) self.x2 = float(a['x2']) self.y2 = float(a['y2']) self.strokeWidth = float(a['stroke-width']) def reverse(self): self.x1, self.x2 = self.x2, self.x1 self.y1, self.y2 = self.y2, self.y1 def start_hash(self): return str(self.x1) + ',' + str(self.y1) def end_hash(self): return str(self.x2) + ',' + str(self.y2) def endpoint(self, direction): if direction == START: return self.start_hash() else: return self.end_hash() def get_other_hash(self, key): h = self.start_hash() if h == key: h = self.end_hash() return h def __repr__(self): return '((%s,%s),(%s,%s),sw:%s)' % (self.x1, self.y1, self.x2, self.y2, self.strokeWidth) class EndpointHash(object): def __init__(self, lines):
def count_overlapping_points(self): count = 0 for key, lines in self.endpoints.iteritems(): l = len(lines) if l > 1: count += 1 return count def _del_line(self, key, line): self.endpoints[key].remove(line) if len(self.endpoints[key]) == 0: del self.endpoints[key] def remove_line(self, line): key = line.start_hash() self._del_line(key, line) self._del_line(line.get_other_hash(key), line) def pop_connected_line(self, line, key): if key in self.endpoints: line = self.endpoints[key][0] self.remove_line(line) return line else: return def parse_svg(fname): print "Parsing '%s'..." % (fname) return etree.parse(fname) def get_lines(svg): lines = [] for l in svg.getroot().iter('{%s}line' % SVG_NS): lines.append(Line(l)) return lines def align_lines(l1, l2): if ( l1.x1 == l2.x1 and l1.y1 == l2.y1 or l1.x2 == l2.x2 and l1.y2 == l2.y2): l2.reverse() def connect_lines(lines, endpoint_hash, line, direction, poly): while True: key = line.endpoint(direction) connected_line = endpoint_hash.pop_connected_line(line, key) if connected_line: if direction == START: poly.insert(0, connected_line) else: poly.append(connected_line) align_lines(line, connected_line) lines.remove(connected_line) line = connected_line else: break def find_polylines(lines, endpoint_hash): polylines = [] while lines: line = lines.pop() endpoint_hash.remove_line(line) poly = [line] connect_lines(lines, endpoint_hash, line, START, poly) connect_lines(lines, endpoint_hash, line, END, poly) polylines.append(poly) return polylines def optimize(svg): lines = get_lines(svg) print '%s line segments found' % len(lines) lines_by_width = defaultdict(list) for l in lines: lines_by_width[l.strokeWidth].append(l) del lines print '%s different stroke widths found:' % len(lines_by_width) for width, lines in lines_by_width.iteritems(): print ' strokeWidth: %s (%s lines)' % (width, len(lines)) polylines = [] for width, lines in lines_by_width.iteritems(): print 'Finding polylines (strokeWidth: %s)... ' % width endpoint_hash = EndpointHash(lines) overlapping_points = endpoint_hash.count_overlapping_points() print (' %s line segments, %s overlapping points' % (len(lines), overlapping_points)), p = find_polylines(lines, endpoint_hash) print '-> %s polylines' % len(p) polylines += p return polylines def write_svg(polylines, outfile): print "Writing '%s'..." % outfile f = open(outfile, 'w') f.write("""<?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg" version="1.1"> """) def point_to_str(x, y): return '%s,%s ' % (x, y) for p in polylines: points = [] for line in p: if not points: points.append(point_to_str(line.x1, line.y1)) points.append(point_to_str(line.x2, line.y2)) f.write('<polyline fill="none" stroke="#000" stroke-width="%s" points="%s"/>\n' % (p[0].strokeWidth, ' '.join(points))) f.write('</svg>\n') f.close() def get_filesize(fname): return os.stat(fname).st_size def print_size_stats(infile, outfile): insize = get_filesize(infile) outsize = get_filesize(outfile) print ('Original file size: %.2fKiB, new file size: %.2fKiB (%.2f)' % (insize / 1024., outsize / 1024., float(outsize) / insize * 100)) def main(): usage = 'Usage: %prog INFILE OUTFILE' parser = OptionParser(usage=usage) options, args = parser.parse_args() if len(args) < 2: parser.error('input and output files must be specified') return 2 infile = args[0] outfile = args[1] svg = parse_svg(infile) polylines = optimize(svg) print '%s polyline(s) found in total' % len(polylines) write_svg(polylines, outfile) print_size_stats(infile, outfile) return 0 if __name__ == '__main__': try: sys.exit(main()) except KeyboardInterrupt: sys.exit(1)
self.endpoints = defaultdict(list) for l in lines: self.endpoints[l.start_hash()].append(l) self.endpoints[l.end_hash()].append(l)
identifier_body
mdui.js
/** * Created by zhangh on 2017/02/12. */ $(function () { //平衡左右侧高度 $('#rightContent').css("minHeight", $('#leftNav').height() > $('#rightContent').height() ? $('#leftNav').height() : $('#rightContent').height()); //展开左侧导航 $(".selected").parents("ul").addClass("open"); $(".selected").parents(".menu_item").children('a').find(".angle-icon").addClass('fa-angle-up').removeClass("fa-angle-down"); //左侧导航伸缩 $('.menu_box a[data-toggle="menuParent"]').on('click', function () { if ($(this).next().hasClass("open")) { $(this).parent().find('ul').removeClass("open") $(this).parent().find('.angle-icon').addClass('fa-angle-down').removeClass("fa-angle-up"); } else { $(this).next().addClass("open") $(this).parent().find('.angle-icon').addClass('fa-angle-up').removeClass("fa-angle-down"); } $('#rightContent').css("minHeight", $('#leftNav').height() > $('#rightContent').height() ? $('#leftNav').height() : $('#rightContent').height()) }) //手机屏幕点击显示隐藏左侧菜单栏 $('#toggleLeftNav').click(function (e) { e.preventDefault(); if ($("#leftNav").is(":hidden")) { $("#leftNav").css('cssText', 'display:block !important'); //如果元素为隐藏,则将它显现 } else { $("#leftNav").css('cssText', 'display:none !important'); //如果元素为显现,则将其隐藏 } $('#leftNav').css({'minHeight': 'auto'}); }) if($(".tablesorter").length > 0) { $(".tablesorter").tablesorter(); } // if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { // $('.selectpicker').selectpicker('mobile'); // } confirmModalClose(); //页面加载后初始化提示信息弹出框 //监听删除按钮点击事件 $('[data-toggle="doAjax"]').each(function () { $(this).click(function (e) { e.preventDefault(); var DelBtn = $(this); confirmModalOpen($(DelBtn).data('info')); // 提示信息 $('#ConfirmModal').find('#btnConfirm').click(function () { var modal = $('#ConfirmModal'); // 获取modal对象 modal.find('button').attr('disabled', true); // 禁用modal按钮 confirmModalInfo('正在处理,请稍后...', ' fa-spinner fa-spin '); //进行ajax处理 CommonAjax($(DelBtn).data('objurl'), 'GET', '', function (data) { if (data['status'] == '200') { confirmModalInfo(data['info'], ' fa-check '); } else if (data['status'] == '300') { confirmModalInfo(data['info'], ''); } setTimeout(function () { window.location.replace(window.location.href); }, 2000); }) }) $('#ConfirmModal').on('hidden.bs.modal', function (e) { e.preventDefault(); confirmModalClose(); }) }); }); //初始化插件 initPlugin(); //从远端的数据源加载完数据之后触发该事件 $('#HandleModal').on('loaded.bs.modal', function () { //load模态框后再次初始化插件 initPlugin(); //selectpicker $(this).find('.selectpicker').each(function () { $(this).selectpicker('refresh'); }) }); //此事件在模态框被隐藏(并且同时在 CSS 过渡效果完成)之后被触发 $('#HandleModal').on('hidden.bs.modal', function () { $(this).removeData('bs.modal'); $(this).find(".modal-content").html('<div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close" id="btnClose{:MCA}"><span aria-hidden="true"><i class="fa fa-times-circle"></i></span></button><h4 class="modal-title" id="{:MCA}HandleModalLabel">提示</h4></div><div class="modal-body text-center fontsize20" style="padding:20px 0;"><i class="fa fa-spinner fa-spin"></i>加载中......</div>'); }); //BEGIN BACK TO TOP $(window).scroll(function () { if ($(this).scrollTop() < 200) { $('#totop').fadeOut(); } else { $('#totop').fadeIn(); } }); $('#totop').on('click', function (e) { e.preventDefault(); $('html, body').animate({scrollTop: 0}, 'fast'); return false; }); //END BACK TO TOP }) /** * 页面加载和异步页面加载时,初始化插件 */ function initPlugin() { //radio默认选中第一个 $('input:radio').each(function () { var $name = $(this).attr('name'); if (!$('input:radio[name=' + $name + ']').is(':checked')) { $('input:radio[name=' + $name + ']').eq(0).attr("checked", true); } }); //selectpicker JiLian $('.selectpicker[data-action="jiLian"]').each(function () { $(this).change(function () { var thisSelect = $(this); CommonAjax(thisSelect.data('link'), 'POST', {param: thisSelect.val()}, function (jiLianResult) { if (jiLianResult.status == '300') { if (!$('#alertBox').length) { $('<div class="alert alert-info alert-dismissible" role="alert" id="alertBox"><button type="button" class="close" style="top:3px;right:-5px;" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button><span id="alertBoxMsg" style="text-align: center;"><i class="fa fa-spinner fa-spin"></i>数据正在处理,请稍等...</span></div>').appendTo('body'); } $('#alertBox').removeClass('alert-info').addClass('alert-danger'); $('#alertBoxMsg').html('<i class="fa fa-exclamation-circle"></i> ' + jiLianResult.info).show(); setTimeout(function () { $('#alertBox').remove(); }, 4000); } else if (jiLianResult.status == '200') { var str = ''; var deptData = jiLianResult.data; for (var i = 0, len = deptData.length; i < len; i++) { str += '<option value="' + deptData[i].id + '">' + deptData[i].name + '</option>'; } $('#' + thisSelect.data('subject')).html(str).selectpicker('refresh').change(); } }); }) }); //kindeditor $('textarea[data-toggle="kindeditor"]').each(function () { createKindeditor($(this).attr('id'), $(this).data()); }); //kindeditorImageUpload $('span[data-toggle="kindeditorImage"]').each(function () { var $obj = $(this); var $editor = KindEditor.editor({ uploadJson: UploadJson, fileManagerJson: FileManagerJson, allowFileManager: true, imageSizeLimit: '2MB', imageFileTypes: '*.jpg;*.jpeg;*.bmp;*.gif;*.png' }); $obj.click(function () { var $this = $(this); $editor.pluginsPath = LibPath + 'kindeditor/plugins/'; $editor.loadPlugin('image', function () { $editor.plugin.imageDialog({ imageUrl: $($this.data('target')).val(), clickFn: function (url, title, width, height, border, align) { console.log($this.data('preview')); $($this.data('target')).val(url); $($this.data('preview')).prop('src', url).show(500); $editor.hideDialog(); } }); }); }) }); //kindeditorFileUpload $('span[data-toggle="kindeditorFile"]').each(function () { var $obj = $(this); var $editor = KindEditor.editor({ uploadJson: UploadJson, fileManagerJson: FileManagerJson, allowFileManager: true }); $obj.click(function () { var $this = $(this); $editor.pluginsPath = LibPath + 'kindeditor/plugins/'; $editor.loadPlugin('insertfile', function () { $editor.plugin.fileDialog({ fileUrl: $($this.data('target')).val(), clickFn: function (url, title) { $($this.data('target')).val(url); $($this.data('preview')).html('选中文件:<a target="_blank" href="' + url + '">' + title + '</a>').show(500); $editor.hideDialog(); } }); }); }) }); //datetimepicker $('input[data-toggle="datetimepicker"]').each(function () { var $options = $(this).data(); if (!$options.hasOwnProperty('format')) $options.format = 'yyyy-mm-dd'; if (!$options.hasOwnProperty("autoclose")) $options.autoclose = true; if (!$options.hasOwnProperty("todayBtn")) $options.todayBtn = true; if (!$options.hasOwnProperty("language")) $options.language = "zh-CN"; if (!$options.hasOwnProperty("minView")) $options.minView = 2; $(this).datetimepicker($options).on('changeDate show', function (e) { $(this).closest('form[data-toggle="validateForm"]').bootstrapValidator('revalidateField', $(this).attr('name')); }); $(this).attr("readonly", "readonly"); }); //validateForm $('form[data-toggle="validateForm"]').each(function () { validateForm($(this), eval($(this).data('field'))); }); $('div[data-toggle="echarts"]').each(function () { var eChart = echarts.init($(this).get(0), 'macarons'); if ($(this).data('method') == 'ajax') { eChart.showLoading(); CommonAjax($(this).data('url'), 'GET', '', function (data) { eChart.hideLoading(); eChart.setOption(data); }) } else if ($(this).data('option') != '') { eChart.setOption($(this).data('option')); } }) } /** * 提示信息弹出框打开 * @param info 提示信息 * @param showBtn 是否显示确认取消按钮 * @param icon 提示信息图标 */ function confirmModalOpen(info, showBtn, icon) { if (!showBtn) showBtn = '1'; if (!icon) icon = 'fa-exclamation-circle'; $('#ConfirmModal').on('show.bs.modal', function (event) { var modal = $(this); confirmModalInfo(info, icon); if (showBtn !== '1') { modal.find('button').hide(); } }) $('#ConfirmModal').modal({ backdrop: 'static', keyboard: false, show: true }) return; } /** * 提示信息弹出框提示文字修改 * @param info 文字信息 * @param icon 图标 */ function confirmModalInfo(info, icon) { if (!icon) icon = 'fa-exclamation-circle'; $('#ConfirmModal').find('.modal-body').html("<i class='fa " + icon + " fontsize30 colorf00'></i>" + info); } /** * 提示信息弹出框关闭 */ function confirm
modal.find('.modal-body').html(''); modal.find('button').removeAttr('disabled').show(); modal.modal('hide'); } /** * 统一ajax方法 * @param url * @param type * @param data * @param success * @constructor */ function CommonAjax(url, type, data, success) { $.ajax({ url: url, type: type, data: data, dataType: 'json', success: function (result) { success && success(result); }, error: function (e) { alert("ajax错误提示: " + e.status + " " + e.statusText); } }); } /** * 统一验证调用方法 * @param $thisForm 需要验证的表单 * @param $field 验证的字段 */ function validateForm($thisForm, $field) { $thisForm.bootstrapValidator({ message: '您输入的信息有误,请仔细检查!', feedbackIcons: { valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-refresh' }, fields: $field }).on('success.form.bv', function (e) { e.preventDefault(); var $form = $(e.target); //获取表单实例 //禁用所有按钮 $('#HandleModal').find('button').attr('disabled', true); $($form).find('button').attr('disabled', true); //显示提示信息 if (!$('#alertBox').length) { $('<div class="alert alert-info alert-dismissible" role="alert" id="alertBox"><button type="button" class="close" style="top:3px;right:-5px;" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button><span id="alertBoxMsg" style="text-align: center;"><i class="fa fa-spinner fa-spin"></i>数据正在处理,请稍等...</span></div>').appendTo('body'); } $('#alertBox').removeClass('alert-success').removeClass('alert-danger').addClass('alert-info'); $('#alertBoxMsg').html('<i class="fa fa-spinner fa-spin"></i>数据正在处理,请稍等...').show(); if (typeof(beforeAjax) == 'function') beforeAjax($form); //ajax处理 CommonAjax($form.attr('action'), 'POST', $form.serialize(), function (data) { if (!$('#alertBox').length) { $('<div class="alert alert-info alert-dismissible" role="alert" id="alertBox"><button type="button" class="close" style="top:3px;right:-5px;" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button><span id="alertBoxMsg" style="text-align: center;"><i class="fa fa-spinner fa-spin"></i>数据正在处理,请稍等...</span></div>').appendTo('body'); } if (data.status == '300') { $('#alertBox').removeClass('alert-info').addClass('alert-danger'); $('#alertBoxMsg').html('<i class="fa fa-exclamation-circle"></i> ' + data.info).show(); //启用所有按钮 $('#HandleModal').find('button').removeAttr('disabled'); $($form).find('button').removeAttr('disabled'); setTimeout(function () { $('#alertBox').remove(); }, 8000); } else if (data.status == '200') { $('#alertBox').removeClass('alert-info').addClass('alert-success'); $('#alertBoxMsg').html('<i class="fa fa-check"></i> ' + data.info).show(); //启用所有按钮 // $('#HandleModal').find('button').removeAttr('disabled'); // $($form).find('button').removeAttr('disabled'); setTimeout(function () { window.location.replace(RefreshUrl); }, 1000); } }); }); } /** * 统一创建kindeditor * @param $objId 对象ID */ function createKindeditor($objId, $options) { KindEditor.create('#' + $objId, { uploadJson: UploadJson, fileManagerJson: FileManagerJson, allowFileManager: true, imageSizeLimit: '2MB', imageUploadLimit: '20', imageFileTypes: '*.jpg;*.jpeg;*.bmp;*.gif;*.png', afterBlur: function () { this.sync(); } }); }
ModalClose() { var modal = $('#ConfirmModal');
conditional_block
mdui.js
/** * Created by zhangh on 2017/02/12. */ $(function () { //平衡左右侧高度 $('#rightContent').css("minHeight", $('#leftNav').height() > $('#rightContent').height() ? $('#leftNav').height() : $('#rightContent').height()); //展开左侧导航 $(".selected").parents("ul").addClass("open"); $(".selected").parents(".menu_item").children('a').find(".angle-icon").addClass('fa-angle-up').removeClass("fa-angle-down"); //左侧导航伸缩 $('.menu_box a[data-toggle="menuParent"]').on('click', function () { if ($(this).next().hasClass("open")) { $(this).parent().find('ul').removeClass("open") $(this).parent().find('.angle-icon').addClass('fa-angle-down').removeClass("fa-angle-up"); } else { $(this).next().addClass("open") $(this).parent().find('.angle-icon').addClass('fa-angle-up').removeClass("fa-angle-down"); } $('#rightContent').css("minHeight", $('#leftNav').height() > $('#rightContent').height() ? $('#leftNav').height() : $('#rightContent').height()) }) //手机屏幕点击显示隐藏左侧菜单栏 $('#toggleLeftNav').click(function (e) { e.preventDefault(); if ($("#leftNav").is(":hidden")) { $("#leftNav").css('cssText', 'display:block !important'); //如果元素为隐藏,则将它显现 } else { $("#leftNav").css('cssText', 'display:none !important'); //如果元素为显现,则将其隐藏 } $('#leftNav').css({'minHeight': 'auto'}); }) if($(".tablesorter").length > 0) { $(".tablesorter").tablesorter(); } // if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { // $('.selectpicker').selectpicker('mobile'); // } confirmModalClose(); //页面加载后初始化提示信息弹出框 //监听删除按钮点击事件 $('[data-toggle="doAjax"]').each(function () { $(this).click(function (e) { e.preventDefault(); var DelBtn = $(this); confirmModalOpen($(DelBtn).data('info')); // 提示信息 $('#ConfirmModal').find('#btnConfirm').click(function () { var modal = $('#ConfirmModal'); // 获取modal对象 modal.find('button').attr('disabled', true); // 禁用modal按钮 confirmModalInfo('正在处理,请稍后...', ' fa-spinner fa-spin '); //进行ajax处理 CommonAjax($(DelBtn).data('objurl'), 'GET', '', function (data) { if (data['status'] == '200') { confirmModalInfo(data['info'], ' fa-check '); } else if (data['status'] == '300') { confirmModalInfo(data['info'], ''); } setTimeout(function () { window.location.replace(window.location.href); }, 2000); }) }) $('#ConfirmModal').on('hidden.bs.modal', function (e) { e.preventDefault(); confirmModalClose(); }) }); }); //初始化插件 initPlugin(); //从远端的数据源加载完数据之后触发该事件 $('#HandleModal').on('loaded.bs.modal', function () { //load模态框后再次初始化插件 initPlugin(); //selectpicker $(this).find('.selectpicker').each(function () { $(this).selectpicker('refresh'); }) }); //此事件在模态框被隐藏(并且同时在 CSS 过渡效果完成)之后被触发 $('#HandleModal').on('hidden.bs.modal', function () { $(this).removeData('bs.modal'); $(this).find(".modal-content").html('<div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close" id="btnClose{:MCA}"><span aria-hidden="true"><i class="fa fa-times-circle"></i></span></button><h4 class="modal-title" id="{:MCA}HandleModalLabel">提示</h4></div><div class="modal-body text-center fontsize20" style="padding:20px 0;"><i class="fa fa-spinner fa-spin"></i>加载中......</div>'); }); //BEGIN BACK TO TOP $(window).scroll(function () { if ($(this).scrollTop() < 200) { $('#totop').fadeOut(); } else { $('#totop').fadeIn(); } }); $('#totop').on('click', function (e) { e.preventDefault(); $('html, body').animate({scrollTop: 0}, 'fast'); return false; }); //END BACK TO TOP }) /** * 页面加载和异步页面加载时,初始化插件 */ function initPlugin() { //radio默认选中第一个 $('input:radio').each(function () { var $name = $(this).attr('name'); if (!$('input:radio[name=' + $name + ']').is(':checked')) { $('input:radio[name=' + $name + ']').eq(0).attr("checked", true); } }); //selectpicker JiLian $('.selectpicker[data-action="jiLian"]').each(function () { $(this).change(function () { var thisSelect = $(this); CommonAjax(thisSelect.data('link'), 'POST', {param: thisSelect.val()}, function (jiLianResult) { if (jiLianResult.status == '300') { if (!$('#alertBox').length) { $('<div class="alert alert-info alert-dismissible" role="alert" id="alertBox"><button type="button" class="close" style="top:3px;right:-5px;" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button><span id="alertBoxMsg" style="text-align: center;"><i class="fa fa-spinner fa-spin"></i>数据正在处理,请稍等...</span></div>').appendTo('body'); } $('#alertBox').removeClass('alert-info').addClass('alert-danger'); $('#alertBoxMsg').html('<i class="fa fa-exclamation-circle"></i> ' + jiLianResult.info).show(); setTimeout(function () { $('#alertBox').remove(); }, 4000); } else if (jiLianResult.status == '200') { var str = ''; var deptData = jiLianResult.data; for (var i = 0, len = deptData.length; i < len; i++) { str += '<option value="' + deptData[i].id + '">' + deptData[i].name + '</option>'; } $('#' + thisSelect.data('subject')).html(str).selectpicker('refresh').change(); } }); }) }); //kindeditor $('textarea[data-toggle="kindeditor"]').each(function () { createKindeditor($(this).attr('id'), $(this).data()); }); //kindeditorImageUpload $('span[data-toggle="kindeditorImage"]').each(function () { var $obj = $(this); var $editor = KindEditor.editor({ uploadJson: UploadJson, fileManagerJson: FileManagerJson, allowFileManager: true, imageSizeLimit: '2MB', imageFileTypes: '*.jpg;*.jpeg;*.bmp;*.gif;*.png' }); $obj.click(function () { var $this = $(this); $editor.pluginsPath = LibPath + 'kindeditor/plugins/'; $editor.loadPlugin('image', function () { $editor.plugin.imageDialog({ imageUrl: $($this.data('target')).val(), clickFn: function (url, title, width, height, border, align) { console.log($this.data('preview')); $($this.data('target')).val(url); $($this.data('preview')).prop('src', url).show(500); $editor.hideDialog(); } }); }); }) }); //kindeditorFileUpload $('span[data-toggle="kindeditorFile"]').each(function () { var $obj = $(this); var $editor = KindEditor.editor({ uploadJson: UploadJson, fileManagerJson: FileManagerJson, allowFileManager: true }); $obj.click(function () { var $this = $(this); $editor.pluginsPath = LibPath + 'kindeditor/plugins/'; $editor.loadPlugin('insertfile', function () { $editor.plugin.fileDialog({ fileUrl: $($this.data('target')).val(), clickFn: function (url, title) { $($this.data('target')).val(url); $($this.data('preview')).html('选中文件:<a target="_blank" href="' + url + '">' + title + '</a>').show(500); $editor.hideDialog(); } }); }); }) }); //datetimepicker $('input[data-toggle="datetimepicker"]').each(function () { var $options = $(this).data(); if (!$options.hasOwnProperty('format')) $options.format = 'yyyy-mm-dd'; if (!$options.hasOwnProperty("autoclose")) $options.autoclose = true; if (!$options.hasOwnProperty("todayBtn")) $options.todayBtn = true; if (!$options.hasOwnProperty("language")) $options.language = "zh-CN"; if (!$options.hasOwnProperty("minView")) $options.minView = 2; $(this).datetimepicker($options).on('changeDate show', function (e) { $(this).closest('form[data-toggle="validateForm"]').bootstrapValidator('revalidateField', $(this).attr('name')); }); $(this).attr("readonly", "readonly"); }); //validateForm $('form[data-toggle="validateForm"]').each(function () { validateForm($(this), eval($(this).data('field'))); }); $('div[data-toggle="echarts"]').each(function () { var eChart = echarts.init($(this).get(0), 'macarons'); if ($(this).data('method') == 'ajax') { eChart.showLoading(); CommonAjax($(this).data('url'), 'GET', '', function (data) { eChart.hideLoading(); eChart.setOption(data); }) } else if ($(this).data('option') != '') { eChart.setOption($(this).data('option')); } }) } /** * 提示信息弹出框打开 * @param info 提示信息 * @param showBtn 是否显示确认取消按钮 * @param icon 提示信息图标 */ function confirmModalOpen(info, showBtn, icon) { if (!showBtn) showBtn = '1'; if (!icon) icon = 'fa-exclamation-circle'; $('#ConfirmModal').on('show.bs.modal', function (event) { var modal = $(this); confirmModalInfo(info, icon); if (showBtn !== '1') { modal.find('button').hide(); } }) $('#ConfirmModal').modal({ backdrop: 'static', keyboard: false, show: true }) return; } /** * 提示信息弹出框提示文字修改 * @param info 文字信息 * @param icon 图标 */ function confirmModalInfo(info, icon) { if (!icon) icon = 'fa-exclamation-circle'; $('#ConfirmModal').find('.modal-body').html("<i class='fa " + icon + " fontsize30 colorf00'></i>" + info); }
*/ function confirmModalClose() { var modal = $('#ConfirmModal'); modal.find('.modal-body').html(''); modal.find('button').removeAttr('disabled').show(); modal.modal('hide'); } /** * 统一ajax方法 * @param url * @param type * @param data * @param success * @constructor */ function CommonAjax(url, type, data, success) { $.ajax({ url: url, type: type, data: data, dataType: 'json', success: function (result) { success && success(result); }, error: function (e) { alert("ajax错误提示: " + e.status + " " + e.statusText); } }); } /** * 统一验证调用方法 * @param $thisForm 需要验证的表单 * @param $field 验证的字段 */ function validateForm($thisForm, $field) { $thisForm.bootstrapValidator({ message: '您输入的信息有误,请仔细检查!', feedbackIcons: { valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-refresh' }, fields: $field }).on('success.form.bv', function (e) { e.preventDefault(); var $form = $(e.target); //获取表单实例 //禁用所有按钮 $('#HandleModal').find('button').attr('disabled', true); $($form).find('button').attr('disabled', true); //显示提示信息 if (!$('#alertBox').length) { $('<div class="alert alert-info alert-dismissible" role="alert" id="alertBox"><button type="button" class="close" style="top:3px;right:-5px;" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button><span id="alertBoxMsg" style="text-align: center;"><i class="fa fa-spinner fa-spin"></i>数据正在处理,请稍等...</span></div>').appendTo('body'); } $('#alertBox').removeClass('alert-success').removeClass('alert-danger').addClass('alert-info'); $('#alertBoxMsg').html('<i class="fa fa-spinner fa-spin"></i>数据正在处理,请稍等...').show(); if (typeof(beforeAjax) == 'function') beforeAjax($form); //ajax处理 CommonAjax($form.attr('action'), 'POST', $form.serialize(), function (data) { if (!$('#alertBox').length) { $('<div class="alert alert-info alert-dismissible" role="alert" id="alertBox"><button type="button" class="close" style="top:3px;right:-5px;" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button><span id="alertBoxMsg" style="text-align: center;"><i class="fa fa-spinner fa-spin"></i>数据正在处理,请稍等...</span></div>').appendTo('body'); } if (data.status == '300') { $('#alertBox').removeClass('alert-info').addClass('alert-danger'); $('#alertBoxMsg').html('<i class="fa fa-exclamation-circle"></i> ' + data.info).show(); //启用所有按钮 $('#HandleModal').find('button').removeAttr('disabled'); $($form).find('button').removeAttr('disabled'); setTimeout(function () { $('#alertBox').remove(); }, 8000); } else if (data.status == '200') { $('#alertBox').removeClass('alert-info').addClass('alert-success'); $('#alertBoxMsg').html('<i class="fa fa-check"></i> ' + data.info).show(); //启用所有按钮 // $('#HandleModal').find('button').removeAttr('disabled'); // $($form).find('button').removeAttr('disabled'); setTimeout(function () { window.location.replace(RefreshUrl); }, 1000); } }); }); } /** * 统一创建kindeditor * @param $objId 对象ID */ function createKindeditor($objId, $options) { KindEditor.create('#' + $objId, { uploadJson: UploadJson, fileManagerJson: FileManagerJson, allowFileManager: true, imageSizeLimit: '2MB', imageUploadLimit: '20', imageFileTypes: '*.jpg;*.jpeg;*.bmp;*.gif;*.png', afterBlur: function () { this.sync(); } }); }
/** * 提示信息弹出框关闭
random_line_split
mdui.js
/** * Created by zhangh on 2017/02/12. */ $(function () { //平衡左右侧高度 $('#rightContent').css("minHeight", $('#leftNav').height() > $('#rightContent').height() ? $('#leftNav').height() : $('#rightContent').height()); //展开左侧导航 $(".selected").parents("ul").addClass("open"); $(".selected").parents(".menu_item").children('a').find(".angle-icon").addClass('fa-angle-up').removeClass("fa-angle-down"); //左侧导航伸缩 $('.menu_box a[data-toggle="menuParent"]').on('click', function () { if ($(this).next().hasClass("open")) { $(this).parent().find('ul').removeClass("open") $(this).parent().find('.angle-icon').addClass('fa-angle-down').removeClass("fa-angle-up"); } else { $(this).next().addClass("open") $(this).parent().find('.angle-icon').addClass('fa-angle-up').removeClass("fa-angle-down"); } $('#rightContent').css("minHeight", $('#leftNav').height() > $('#rightContent').height() ? $('#leftNav').height() : $('#rightContent').height()) }) //手机屏幕点击显示隐藏左侧菜单栏 $('#toggleLeftNav').click(function (e) { e.preventDefault(); if ($("#leftNav").is(":hidden")) { $("#leftNav").css('cssText', 'display:block !important'); //如果元素为隐藏,则将它显现 } else { $("#leftNav").css('cssText', 'display:none !important'); //如果元素为显现,则将其隐藏 } $('#leftNav').css({'minHeight': 'auto'}); }) if($(".tablesorter").length > 0) { $(".tablesorter").tablesorter(); } // if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { // $('.selectpicker').selectpicker('mobile'); // } confirmModalClose(); //页面加载后初始化提示信息弹出框 //监听删除按钮点击事件 $('[data-toggle="doAjax"]').each(function () { $(this).click(function (e) { e.preventDefault(); var DelBtn = $(this); confirmModalOpen($(DelBtn).data('info')); // 提示信息 $('#ConfirmModal').find('#btnConfirm').click(function () { var modal = $('#ConfirmModal'); // 获取modal对象 modal.find('button').attr('disabled', true); // 禁用modal按钮 confirmModalInfo('正在处理,请稍后...', ' fa-spinner fa-spin '); //进行ajax处理 CommonAjax($(DelBtn).data('objurl'), 'GET', '', function (data) { if (data['status'] == '200') { confirmModalInfo(data['info'], ' fa-check '); } else if (data['status'] == '300') { confirmModalInfo(data['info'], ''); } setTimeout(function () { window.location.replace(window.location.href); }, 2000); }) }) $('#ConfirmModal').on('hidden.bs.modal', function (e) { e.preventDefault(); confirmModalClose(); }) }); }); //初始化插件 initPlugin(); //从远端的数据源加载完数据之后触发该事件 $('#HandleModal').on('loaded.bs.modal', function () { //load模态框后再次初始化插件 initPlugin(); //selectpicker $(this).find('.selectpicker').each(function () { $(this).selectpicker('refresh'); }) }); //此事件在模态框被隐藏(并且同时在 CSS 过渡效果完成)之后被触发 $('#HandleModal').on('hidden.bs.modal', function () { $(this).removeData('bs.modal'); $(this).find(".modal-content").html('<div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close" id="btnClose{:MCA}"><span aria-hidden="true"><i class="fa fa-times-circle"></i></span></button><h4 class="modal-title" id="{:MCA}HandleModalLabel">提示</h4></div><div class="modal-body text-center fontsize20" style="padding:20px 0;"><i class="fa fa-spinner fa-spin"></i>加载中......</div>'); }); //BEGIN BACK TO TOP $(window).scroll(function () { if ($(this).scrollTop() < 200) { $('#totop').fadeOut(); } else { $('#totop').fadeIn(); } }); $('#totop').on('click', function (e) { e.preventDefault(); $('html, body').animate({scrollTop: 0}, 'fast'); return false; }); //END BACK TO TOP }) /** * 页面加载和异步页面加载时,初始化插件 */ function initPlugin() { //radio默认选中第一个 $('input:radio').each(function () { var $name = $(this).attr('name'); if (!$('input:radio[name=' + $name + ']').is(':checked')) { $('input:radio[name=' + $name + ']').eq(0).attr("checked", true); } }); //selectpicker JiLian $('.selectpicker[data-action="jiLian"]').each(function () { $(this).change(function () { var thisSelect = $(this); CommonAjax(thisSelect.data('link'), 'POST', {param: thisSelect.val()}, function (jiLianResult) { if (jiLianResult.status == '300') { if (!$('#alertBox').length) { $('<div class="alert alert-info alert-dismissible" role="alert" id="alertBox"><button type="button" class="close" style="top:3px;right:-5px;" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button><span id="alertBoxMsg" style="text-align: center;"><i class="fa fa-spinner fa-spin"></i>数据正在处理,请稍等...</span></div>').appendTo('body'); } $('#alertBox').removeClass('alert-info').addClass('alert-danger'); $('#alertBoxMsg').html('<i class="fa fa-exclamation-circle"></i> ' + jiLianResult.info).show(); setTimeout(function () { $('#alertBox').remove(); }, 4000); } else if (jiLianResult.status == '200') { var str = ''; var deptData = jiLianResult.data; for (var i = 0, len = deptData.length; i < len; i++) { str += '<option value="' + deptData[i].id + '">' + deptData[i].name + '</option>'; } $('#' + thisSelect.data('subject')).html(str).selectpicker('refresh').change(); } }); }) }); //kindeditor $('textarea[data-toggle="kindeditor"]').each(function () { createKindeditor($(this).attr('id'), $(this).data()); }); //kindeditorImageUpload $('span[data-toggle="kindeditorImage"]').each(function () { var $obj = $(this); var $editor = KindEditor.editor({ uploadJson: UploadJson, fileManagerJson: FileManagerJson, allowFileManager: true, imageSizeLimit: '2MB', imageFileTypes: '*.jpg;*.jpeg;*.bmp;*.gif;*.png' }); $obj.click(function () { var $this = $(this); $editor.pluginsPath = LibPath + 'kindeditor/plugins/'; $editor.loadPlugin('image', function () { $editor.plugin.imageDialog({ imageUrl: $($this.data('target')).val(), clickFn: function (url, title, width, height, border, align) { console.log($this.data('preview')); $($this.data('target')).val(url); $($this.data('preview')).prop('src', url).show(500); $editor.hideDialog(); } }); }); }) }); //kindeditorFileUpload $('span[data-toggle="kindeditorFile"]').each(function () { var $obj = $(this); var $editor = KindEditor.editor({ uploadJson: UploadJson, fileManagerJson: FileManagerJson, allowFileManager: true }); $obj.click(function () { var $this = $(this); $editor.pluginsPath = LibPath + 'kindeditor/plugins/'; $editor.loadPlugin('insertfile', function () { $editor.plugin.fileDialog({ fileUrl: $($this.data('target')).val(), clickFn: function (url, title) { $($this.data('target')).val(url); $($this.data('preview')).html('选中文件:<a target="_blank" href="' + url + '">' + title + '</a>').show(500); $editor.hideDialog(); } }); }); }) }); //datetimepicker $('input[data-toggle="datetimepicker"]').each(function () { var $options = $(this).data(); if (!$options.hasOwnProperty('format')) $options.format = 'yyyy-mm-dd'; if (!$options.hasOwnProperty("autoclose")) $options.autoclose = true; if (!$options.hasOwnProperty("todayBtn")) $options.todayBtn = true; if (!$options.hasOwnProperty("language")) $options.language = "zh-CN"; if (!$options.hasOwnProperty("minView")) $options.minView = 2; $(this).datetimepicker($options).on('changeDate show', function (e) { $(this).closest('form[data-toggle="validateForm"]').bootstrapValidator('revalidateField', $(this).attr('name')); }); $(this).attr("readonly", "readonly"); }); //validateForm $('form[data-toggle="validateForm"]').each(function () { validateForm($(this), eval($(this).data('field'))); }); $('div[data-toggle="echarts"]').each(function () { var eChart = echarts.init($(this).get(0), 'macarons'); if ($(this).data('method') == 'ajax') { eChart.showLoading(); CommonAjax($(this).data('url'), 'GET', '', function (data) { eChart.hideLoading(); eChart.setOption(data); }) } else if ($(this).data('option') != '') { eChart.setOption($(this).data('option')); } }) } /** * 提示信息弹出框打开 * @param info 提示信息 * @param showBtn 是否显示确认取消按钮 * @param icon 提示信息图标 */ function confirmModalOpen(info, showBtn, icon) { if (!showBtn) showBtn = '1'; if (!icon) icon = 'fa-exclamation-circle'; $('#ConfirmModal').on('show.bs.modal', function (event) { var modal = $(this); confirmModalInfo(info, icon); if (showBtn !== '1') { modal.find('button').hide(); } }) $('#ConfirmModal').modal({ backdrop: 'static', keyboard: false, show: true }) return; } /** * 提示信息弹出框提示文字修改 * @
* @param icon 图标 */ function confirmModalInfo(info, icon) { if (!icon) icon = 'fa-exclamation-circle'; $('#ConfirmModal').find('.modal-body').html("<i class='fa " + icon + " fontsize30 colorf00'></i>" + info); } /** * 提示信息弹出框关闭 */ function confirmModalClose() { var modal = $('#ConfirmModal'); modal.find('.modal-body').html(''); modal.find('button').removeAttr('disabled').show(); modal.modal('hide'); } /** * 统一ajax方法 * @param url * @param type * @param data * @param success * @constructor */ function CommonAjax(url, type, data, success) { $.ajax({ url: url, type: type, data: data, dataType: 'json', success: function (result) { success && success(result); }, error: function (e) { alert("ajax错误提示: " + e.status + " " + e.statusText); } }); } /** * 统一验证调用方法 * @param $thisForm 需要验证的表单 * @param $field 验证的字段 */ function validateForm($thisForm, $field) { $thisForm.bootstrapValidator({ message: '您输入的信息有误,请仔细检查!', feedbackIcons: { valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-refresh' }, fields: $field }).on('success.form.bv', function (e) { e.preventDefault(); var $form = $(e.target); //获取表单实例 //禁用所有按钮 $('#HandleModal').find('button').attr('disabled', true); $($form).find('button').attr('disabled', true); //显示提示信息 if (!$('#alertBox').length) { $('<div class="alert alert-info alert-dismissible" role="alert" id="alertBox"><button type="button" class="close" style="top:3px;right:-5px;" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button><span id="alertBoxMsg" style="text-align: center;"><i class="fa fa-spinner fa-spin"></i>数据正在处理,请稍等...</span></div>').appendTo('body'); } $('#alertBox').removeClass('alert-success').removeClass('alert-danger').addClass('alert-info'); $('#alertBoxMsg').html('<i class="fa fa-spinner fa-spin"></i>数据正在处理,请稍等...').show(); if (typeof(beforeAjax) == 'function') beforeAjax($form); //ajax处理 CommonAjax($form.attr('action'), 'POST', $form.serialize(), function (data) { if (!$('#alertBox').length) { $('<div class="alert alert-info alert-dismissible" role="alert" id="alertBox"><button type="button" class="close" style="top:3px;right:-5px;" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button><span id="alertBoxMsg" style="text-align: center;"><i class="fa fa-spinner fa-spin"></i>数据正在处理,请稍等...</span></div>').appendTo('body'); } if (data.status == '300') { $('#alertBox').removeClass('alert-info').addClass('alert-danger'); $('#alertBoxMsg').html('<i class="fa fa-exclamation-circle"></i> ' + data.info).show(); //启用所有按钮 $('#HandleModal').find('button').removeAttr('disabled'); $($form).find('button').removeAttr('disabled'); setTimeout(function () { $('#alertBox').remove(); }, 8000); } else if (data.status == '200') { $('#alertBox').removeClass('alert-info').addClass('alert-success'); $('#alertBoxMsg').html('<i class="fa fa-check"></i> ' + data.info).show(); //启用所有按钮 // $('#HandleModal').find('button').removeAttr('disabled'); // $($form).find('button').removeAttr('disabled'); setTimeout(function () { window.location.replace(RefreshUrl); }, 1000); } }); }); } /** * 统一创建kindeditor * @param $objId 对象ID */ function createKindeditor($objId, $options) { KindEditor.create('#' + $objId, { uploadJson: UploadJson, fileManagerJson: FileManagerJson, allowFileManager: true, imageSizeLimit: '2MB', imageUploadLimit: '20', imageFileTypes: '*.jpg;*.jpeg;*.bmp;*.gif;*.png', afterBlur: function () { this.sync(); } }); }
param info 文字信息
identifier_name
mdui.js
/** * Created by zhangh on 2017/02/12. */ $(function () { //平衡左右侧高度 $('#rightContent').css("minHeight", $('#leftNav').height() > $('#rightContent').height() ? $('#leftNav').height() : $('#rightContent').height()); //展开左侧导航 $(".selected").parents("ul").addClass("open"); $(".selected").parents(".menu_item").children('a').find(".angle-icon").addClass('fa-angle-up').removeClass("fa-angle-down"); //左侧导航伸缩 $('.menu_box a[data-toggle="menuParent"]').on('click', function () { if ($(this).next().hasClass("open")) { $(this).parent().find('ul').removeClass("open") $(this).parent().find('.angle-icon').addClass('fa-angle-down').removeClass("fa-angle-up"); } else { $(this).next().addClass("open") $(this).parent().find('.angle-icon').addClass('fa-angle-up').removeClass("fa-angle-down"); } $('#rightContent').css("minHeight", $('#leftNav').height() > $('#rightContent').height() ? $('#leftNav').height() : $('#rightContent').height()) }) //手机屏幕点击显示隐藏左侧菜单栏 $('#toggleLeftNav').click(function (e) { e.preventDefault(); if ($("#leftNav").is(":hidden")) { $("#leftNav").css('cssText', 'display:block !important'); //如果元素为隐藏,则将它显现 } else { $("#leftNav").css('cssText', 'display:none !important'); //如果元素为显现,则将其隐藏 } $('#leftNav').css({'minHeight': 'auto'}); }) if($(".tablesorter").length > 0) { $(".tablesorter").tablesorter(); } // if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { // $('.selectpicker').selectpicker('mobile'); // } confirmModalClose(); //页面加载后初始化提示信息弹出框 //监听删除按钮点击事件 $('[data-toggle="doAjax"]').each(function () { $(this).click(function (e) { e.preventDefault(); var DelBtn = $(this); confirmModalOpen($(DelBtn).data('info')); // 提示信息 $('#ConfirmModal').find('#btnConfirm').click(function () { var modal = $('#ConfirmModal'); // 获取modal对象 modal.find('button').attr('disabled', true); // 禁用modal按钮 confirmModalInfo('正在处理,请稍后...', ' fa-spinner fa-spin '); //进行ajax处理 CommonAjax($(DelBtn).data('objurl'), 'GET', '', function (data) { if (data['status'] == '200') { confirmModalInfo(data['info'], ' fa-check '); } else if (data['status'] == '300') { confirmModalInfo(data['info'], ''); } setTimeout(function () { window.location.replace(window.location.href); }, 2000); }) }) $('#ConfirmModal').on('hidden.bs.modal', function (e) { e.preventDefault(); confirmModalClose(); }) }); }); //初始化插件 initPlugin(); //从远端的数据源加载完数据之后触发该事件 $('#HandleModal').on('loaded.bs.modal', function () { //load模态框后再次初始化插件 initPlugin(); //selectpicker $(this).find('.selectpicker').each(function () { $(this).selectpicker('refresh'); }) }); //此事件在模态框被隐藏(并且同时在 CSS 过渡效果完成)之后被触发 $('#HandleModal').on('hidden.bs.modal', function () { $(this).removeData('bs.modal'); $(this).find(".modal-content").html('<div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close" id="btnClose{:MCA}"><span aria-hidden="true"><i class="fa fa-times-circle"></i></span></button><h4 class="modal-title" id="{:MCA}HandleModalLabel">提示</h4></div><div class="modal-body text-center fontsize20" style="padding:20px 0;"><i class="fa fa-spinner fa-spin"></i>加载中......</div>'); }); //BEGIN BACK TO TOP $(window).scroll(function () { if ($(this).scrollTop() < 200) { $('#totop').fadeOut(); } else { $('#totop').fadeIn(); } }); $('#totop').on('click', function (e) { e.preventDefault(); $('html, body').animate({scrollTop: 0}, 'fast'); return false; }); //END BACK TO TOP }) /** * 页面加载和异步页面加载时,初始化插件 */ function initPlugin() { //radio默认选中第一个 $('input:radio').each(function () { var $name = $(this).attr('name'); if (!$('input:radio[name=' + $name + ']').is(':checked')) { $('input:radio[name=' + $name + ']').eq(0).attr("checked", true); } }); //selectpicker JiLian $('.selectpicker[data-action="jiLian"]').each(function () { $(this).change(function () { var thisSelect = $(this); CommonAjax(thisSelect.data('link'), 'POST', {param: thisSelect.val()}, function (jiLianResult) { if (jiLianResult.status == '300') { if (!$('#alertBox').length) { $('<div class="alert alert-info alert-dismissible" role="alert" id="alertBox"><button type="button" class="close" style="top:3px;right:-5px;" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button><span id="alertBoxMsg" style="text-align: center;"><i class="fa fa-spinner fa-spin"></i>数据正在处理,请稍等...</span></div>').appendTo('body'); } $('#alertBox').removeClass('alert-info').addClass('alert-danger'); $('#alertBoxMsg').html('<i class="fa fa-exclamation-circle"></i> ' + jiLianResult.info).show(); setTimeout(function () { $('#alertBox').remove(); }, 4000); } else if (jiLianResult.status == '200') { var str = ''; var deptData = jiLianResult.data; for (var i = 0, len = deptData.length; i < len; i++) { str += '<option value="' + deptData[i].id + '">' + deptData[i].name + '</option>'; } $('#' + thisSelect.data('subject')).html(str).selectpicker('refresh').change(); } }); }) }); //kindeditor $('textarea[data-toggle="kindeditor"]').each(function () { createKindeditor($(this).attr('id'), $(this).data()); }); //kindeditorImageUpload $('span[data-toggle="kindeditorImage"]').each(function () { var $obj = $(this); var $editor = KindEditor.editor({ uploadJson: UploadJson, fileManagerJson: FileManagerJson, allowFileManager: true, imageSizeLimit: '2MB', imageFileTypes: '*.jpg;*.jpeg;*.bmp;*.gif;*.png' }); $obj.click(function () { var $this = $(this); $editor.pluginsPath = LibPath + 'kindeditor/plugins/'; $editor.loadPlugin('image', function () { $editor.plugin.imageDialog({ imageUrl: $($this.data('target')).val(), clickFn: function (url, title, width, height, border, align) { console.log($this.data('preview')); $($this.data('target')).val(url); $($this.data('preview')).prop('src', url).show(500); $editor.hideDialog(); } }); }); }) }); //kindeditorFileUpload $('span[data-toggle="kindeditorFile"]').each(function () { var $obj = $(this); var $editor = KindEditor.editor({ uploadJson: UploadJson, fileManagerJson: FileManagerJson, allowFileManager: true }); $obj.click(function () { var $this = $(this); $editor.pluginsPath = LibPath + 'kindeditor/plugins/'; $editor.loadPlugin('insertfile', function () { $editor.plugin.fileDialog({ fileUrl: $($this.data('target')).val(), clickFn: function (url, title) { $($this.data('target')).val(url); $($this.data('preview')).html('选中文件:<a target="_blank" href="' + url + '">' + title + '</a>').show(500); $editor.hideDialog(); } }); }); }) }); //datetimepicker $('input[data-toggle="datetimepicker"]').each(function () { var $options = $(this).data(); if (!$options.hasOwnProperty('format')) $options.format = 'yyyy-mm-dd'; if (!$options.hasOwnProperty("autoclose")) $options.autoclose = true; if (!$options.hasOwnProperty("todayBtn")) $options.todayBtn = true; if (!$options.hasOwnProperty("language")) $options.language = "zh-CN"; if (!$options.hasOwnProperty("minView")) $options.minView = 2; $(this).datetimepicker($options).on('changeDate show', function (e) { $(this).closest('form[data-toggle="validateForm"]').bootstrapValidator('revalidateField', $(this).attr('name')); }); $(this).attr("readonly", "readonly"); }); //validateForm $('form[data-toggle="validateForm"]').each(function () { validateForm($(this), eval($(this).data('field'))); }); $('div[data-toggle="echarts"]').each(function () { var eChart = echarts.init($(this).get(0), 'macarons'); if ($(this).data('method') == 'ajax') { eChart.showLoading(); CommonAjax($(this).data('url'), 'GET', '', function (data) { eChart.hideLoading(); eChart.setOption(data); }) } else if ($(this).data('option') != '') { eChart.setOption($(this).data('option')); } }) } /** * 提示信息弹出框打开 * @param info 提示信息 * @param showBtn 是否显示确认取消按钮 * @param icon 提示信息图标 */ function confirmModalOpen(info, showBtn, icon) { if (!showBtn) showBtn = '1'; if (!icon) icon = 'fa-exclamation-circle'; $('#ConfirmModal').on('show.bs.modal', function (event) { var modal = $(this); confirmModalInfo(info, icon); if (showBtn !== '1') { modal.find('button').hide(); } }) $('#ConfirmModal').modal({ backdrop: 'static', keyboard: false, show: true }) return; } /** * 提示信息弹出框提示文字修改 * @param info 文字信息 * @param icon 图标 */ function confirmModalInfo(info, icon) { if (!icon) icon = 'fa-exclamation-circle'; $('#ConfirmModal').find('.modal-body').html("<i class='fa " + icon + " fontsize30 colorf00'></i>" + info); } /** * 提示信息弹出框关闭 */ function confirmModalClose() { var modal = $('#ConfirmModal'); modal.find('.modal-body').html(''); modal.find('button').removeAttr('disabled').show(); modal.modal('hide'); } /** * 统一ajax方法 * @param url * @param type * @param data * @param success * @constructor */ function CommonAjax(url, type, data, success) { $
esult); }, error: function (e) { alert("ajax错误提示: " + e.status + " " + e.statusText); } }); } /** * 统一验证调用方法 * @param $thisForm 需要验证的表单 * @param $field 验证的字段 */ function validateForm($thisForm, $field) { $thisForm.bootstrapValidator({ message: '您输入的信息有误,请仔细检查!', feedbackIcons: { valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-refresh' }, fields: $field }).on('success.form.bv', function (e) { e.preventDefault(); var $form = $(e.target); //获取表单实例 //禁用所有按钮 $('#HandleModal').find('button').attr('disabled', true); $($form).find('button').attr('disabled', true); //显示提示信息 if (!$('#alertBox').length) { $('<div class="alert alert-info alert-dismissible" role="alert" id="alertBox"><button type="button" class="close" style="top:3px;right:-5px;" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button><span id="alertBoxMsg" style="text-align: center;"><i class="fa fa-spinner fa-spin"></i>数据正在处理,请稍等...</span></div>').appendTo('body'); } $('#alertBox').removeClass('alert-success').removeClass('alert-danger').addClass('alert-info'); $('#alertBoxMsg').html('<i class="fa fa-spinner fa-spin"></i>数据正在处理,请稍等...').show(); if (typeof(beforeAjax) == 'function') beforeAjax($form); //ajax处理 CommonAjax($form.attr('action'), 'POST', $form.serialize(), function (data) { if (!$('#alertBox').length) { $('<div class="alert alert-info alert-dismissible" role="alert" id="alertBox"><button type="button" class="close" style="top:3px;right:-5px;" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button><span id="alertBoxMsg" style="text-align: center;"><i class="fa fa-spinner fa-spin"></i>数据正在处理,请稍等...</span></div>').appendTo('body'); } if (data.status == '300') { $('#alertBox').removeClass('alert-info').addClass('alert-danger'); $('#alertBoxMsg').html('<i class="fa fa-exclamation-circle"></i> ' + data.info).show(); //启用所有按钮 $('#HandleModal').find('button').removeAttr('disabled'); $($form).find('button').removeAttr('disabled'); setTimeout(function () { $('#alertBox').remove(); }, 8000); } else if (data.status == '200') { $('#alertBox').removeClass('alert-info').addClass('alert-success'); $('#alertBoxMsg').html('<i class="fa fa-check"></i> ' + data.info).show(); //启用所有按钮 // $('#HandleModal').find('button').removeAttr('disabled'); // $($form).find('button').removeAttr('disabled'); setTimeout(function () { window.location.replace(RefreshUrl); }, 1000); } }); }); } /** * 统一创建kindeditor * @param $objId 对象ID */ function createKindeditor($objId, $options) { KindEditor.create('#' + $objId, { uploadJson: UploadJson, fileManagerJson: FileManagerJson, allowFileManager: true, imageSizeLimit: '2MB', imageUploadLimit: '20', imageFileTypes: '*.jpg;*.jpeg;*.bmp;*.gif;*.png', afterBlur: function () { this.sync(); } }); }
.ajax({ url: url, type: type, data: data, dataType: 'json', success: function (result) { success && success(r
identifier_body
polyfills.ts
/** * This file includes polyfills needed by Angular and is loaded before the app. * You can add your own extra polyfills to this file. * * This file is divided into 2 sections: * 1. Browser polyfills. These are applied before loading ZoneJS and are * sorted by browsers. * 2. Application imports. Files imported after ZoneJS that should be loaded * before your main file. * * The current setup is for so-called "evergreen" browsers; the last versions of * browsers that automatically update themselves. This includes Safari >= 10, * Chrome >= 55 (including Opera), Edge >= 13 on the desktop, and iOS 10 and * Chrome on mobile. * * Learn more in https://angular.io/guide/browser-support */ /*************************************************************************************************** * BROWSER POLYFILLS */ /** IE10 and IE11 requires the following for NgClass support on SVG elements */ // import 'classlist.js'; // Run `npm install --save classlist.js`. /** * Web Animations `@angular/platform-browser/animations` * Only required if AnimationBuilder is used within the application and using * IE/Edge or Safari. Standard animation support in Angular DOES NOT require any * polyfills (as of Angular 6.0). */ // import 'web-animations-js'; // Run `npm install --save web-animations-js`. /** * By default, zone.js will patch all possible macroTask and DomEvents * user can disable parts of macroTask/DomEvents patch by setting following * flags because those flags need to be set before `zone.js` being loaded, and * webpack will put import in the top of bundle, so user need to create a * separate file in this directory (for example: zone-flags.ts), and put the * following flags into that file, and then add the following code before * importing zone.js. import './zone-flags.ts'; * * The flags allowed in zone-flags.ts are listed here.
* (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch * requestAnimationFrame (window as any).__Zone_disable_on_property = true; // * disable patch onProperty such as onclick (window as * any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable * patch specified eventNames * * in IE/Edge developer tools, the addEventListener will also be wrapped by * zone.js with the following flag, it will bypass `zone.js` patch for IE/Edge * * (window as any).__Zone_enable_cross_context_check = true; * */ /*************************************************************************************************** * Zone JS is required by default for Angular itself. */ import 'zone.js/dist/zone'; // Included with Angular CLI. /*************************************************************************************************** * APPLICATION IMPORTS */ import '@angular/localize/init';
* * The following flags will work for all browsers. *
random_line_split
url_monitor.py
#!/usr/bin/env python # -*- encoding:utf-8 -*- __author__ = 'kairong' #解决crontab中无法执行的问题 import sys reload(sys) sys.setdefaultencoding('utf8') import ConfigParser import MySQLdb import requests import re from socket import socket, SOCK_DGRAM, AF_INET from multiprocessing import Process ###函数声明区域 def get_localIP(): '''获取本地ip''' s = socket(AF_I
"" return cf.get(main, name) def check_url(id, url, keyword, method='GET'): '''检查域名和关键词,并把结果写入db''' r = requests.get(url) if r.status_code <=400 and re.search(unicode(keyword), r.text): c_result = 0 else: c_result = 1 status_2_db(id, c_result) def status_2_db(id, status): '''把结果写入db''' conn = MySQLdb.connect(host=db_hostname, user=db_user, passwd=db_pass, db='url_mon',charset='utf8') cur = conn.cursor() sql_get_id_status = "select status_code from status_code where ID = %d and rep_point = '%s' ;" %(id, local_ip) cur.execute(sql_get_id_status) last_code = cur.fetchone() if last_code: last_code = last_code[0] cur_code = last_code * status + status sql_update_id_status = "update status_code set status_code = %d, rep_time = CURRENT_TIMESTAMP where ID = %d and rep_point = '%s';" %(cur_code, id, local_ip) cur.execute(sql_update_id_status) else: cur_code = status sql_into_id_status = "insert into status_code(ID, status_code, rep_point) value(%d, %d, '%s')" %(id, cur_code, local_ip) cur.execute(sql_into_id_status) conn.commit() conn.close() def main(): conn = MySQLdb.connect(host=db_hostname, user=db_user, passwd='test', db='url_mon',charset='utf8') cur = conn.cursor() cur.execute("select * from montior_url;") while True: line = cur.fetchone() if not line: break c_id, c_domain, c_location, c_method, c_keyword = line[0], line[1], line[2], line[3], line[4] c_url = "http://%s%s" % (c_domain,c_location) if c_method == line[5]: c_post_d = line[6] Process(target=check_url, args=(c_id, c_url, c_keyword)).start() ###变量获取区域 local_ip = get_localIP() cf = ConfigParser.ConfigParser() cf.read("./local_config") db_hostname = get_args("DB", "db_host") db_user = get_args("DB", "username") db_pass = get_args("DB", "passwd") db_default = get_args("DB", "db") if __name__ == "__main__": main()
NET, SOCK_DGRAM) s.connect(('google.com', 0)) return s.getsockname()[0] def get_args(main, name): """获取配置"
identifier_body
url_monitor.py
#!/usr/bin/env python # -*- encoding:utf-8 -*- __author__ = 'kairong' #解决crontab中无法执行的问题 import sys reload(sys) sys.setdefaultencoding('utf8') import ConfigParser import MySQLdb import requests import re from socket import socket, SOCK_DGRAM, AF_INET from multiprocessing import Process ###函数声明区域 def get_localIP(): '''获取本地ip''' s = socket(AF_INET, SOCK_DGRAM) s.connect(('google.com', 0)) return s.getsockname()[0] def get_args(main, name): """获取配置""" return cf.get(main, name) def check_url(id, url, keyword, method='GET'): '
词,并把结果写入db''' r = requests.get(url) if r.status_code <=400 and re.search(unicode(keyword), r.text): c_result = 0 else: c_result = 1 status_2_db(id, c_result) def status_2_db(id, status): '''把结果写入db''' conn = MySQLdb.connect(host=db_hostname, user=db_user, passwd=db_pass, db='url_mon',charset='utf8') cur = conn.cursor() sql_get_id_status = "select status_code from status_code where ID = %d and rep_point = '%s' ;" %(id, local_ip) cur.execute(sql_get_id_status) last_code = cur.fetchone() if last_code: last_code = last_code[0] cur_code = last_code * status + status sql_update_id_status = "update status_code set status_code = %d, rep_time = CURRENT_TIMESTAMP where ID = %d and rep_point = '%s';" %(cur_code, id, local_ip) cur.execute(sql_update_id_status) else: cur_code = status sql_into_id_status = "insert into status_code(ID, status_code, rep_point) value(%d, %d, '%s')" %(id, cur_code, local_ip) cur.execute(sql_into_id_status) conn.commit() conn.close() def main(): conn = MySQLdb.connect(host=db_hostname, user=db_user, passwd='test', db='url_mon',charset='utf8') cur = conn.cursor() cur.execute("select * from montior_url;") while True: line = cur.fetchone() if not line: break c_id, c_domain, c_location, c_method, c_keyword = line[0], line[1], line[2], line[3], line[4] c_url = "http://%s%s" % (c_domain,c_location) if c_method == line[5]: c_post_d = line[6] Process(target=check_url, args=(c_id, c_url, c_keyword)).start() ###变量获取区域 local_ip = get_localIP() cf = ConfigParser.ConfigParser() cf.read("./local_config") db_hostname = get_args("DB", "db_host") db_user = get_args("DB", "username") db_pass = get_args("DB", "passwd") db_default = get_args("DB", "db") if __name__ == "__main__": main()
''检查域名和关键
identifier_name
url_monitor.py
#!/usr/bin/env python # -*- encoding:utf-8 -*- __author__ = 'kairong' #解决crontab中无法执行的问题 import sys reload(sys) sys.setdefaultencoding('utf8') import ConfigParser import MySQLdb import requests import re from socket import socket, SOCK_DGRAM, AF_INET from multiprocessing import Process ###函数声明区域 def get_localIP(): '''获取本地ip''' s = socket(AF_INET, SOCK_DGRAM) s.connect(('google.com', 0)) return s.getsockname()[0] def get_args(main, name): """获取配置""" return cf.get(main, name) def check_url(id, url, keyword, method='GET'): '''检查域名和关键词,并把结果写入db''' r = requests.get(url) if r.status_code <=400 and re.search(unicode(keyword), r.text): c_result = 0 else: c_result = 1 status_2_db(id, c_result) def status_2_db(id, status): '''把结果写入db''' conn = MySQLdb.connect(host=db_hostname, user=db_user, passwd=db_pass, db='url_mon',charset='utf8') cur = conn.cursor() sql_get_id_status = "select status_code from status_code where ID = %d and rep_point = '%s' ;" %(id, local_ip) cur.execute(sql_get_id_status) last_code = cur.fetchone() if last_code: last_code = last_code[0] cur_code = last_code * status + status sql_update_id_status = "update status_code set status_code = %d, rep_time = CURRENT_TIMESTAMP where ID = %d and rep_point = '%s';" %(cur_code, id, local_ip) cur.execute(sql_update_id_status) else: cur_code = status sql_into_id_status = "insert into status_code(ID, status_code, rep_point) value(%d, %d, '%s')" %(id, cur_code, local_ip) cur.execute(sql_into_id_status) conn.commit()
cur = conn.cursor() cur.execute("select * from montior_url;") while True: line = cur.fetchone() if not line: break c_id, c_domain, c_location, c_method, c_keyword = line[0], line[1], line[2], line[3], line[4] c_url = "http://%s%s" % (c_domain,c_location) if c_method == line[5]: c_post_d = line[6] Process(target=check_url, args=(c_id, c_url, c_keyword)).start() ###变量获取区域 local_ip = get_localIP() cf = ConfigParser.ConfigParser() cf.read("./local_config") db_hostname = get_args("DB", "db_host") db_user = get_args("DB", "username") db_pass = get_args("DB", "passwd") db_default = get_args("DB", "db") if __name__ == "__main__": main()
conn.close() def main(): conn = MySQLdb.connect(host=db_hostname, user=db_user, passwd='test', db='url_mon',charset='utf8')
random_line_split
url_monitor.py
#!/usr/bin/env python # -*- encoding:utf-8 -*- __author__ = 'kairong' #解决crontab中无法执行的问题 import sys reload(sys) sys.setdefaultencoding('utf8') import ConfigParser import MySQLdb import requests import re from socket import socket, SOCK_DGRAM, AF_INET from multiprocessing import Process ###函数声明区域 def get_localIP(): '''获取本地ip''' s = socket(AF_INET, SOCK_DGRAM) s.connect(('google.com', 0)) return s.getsockname()[0] def get_args(main, name): """获取配置""" return cf.get(main, name) def check_url(id, url, keyword, method='GET'): '''检查域名和关键词,并把结果写入db''' r = requests.get(url) if r.status_code <=400 and re.search(unicode(keyword), r.text): c_result = 0 else: c_result = 1 status_2_db(id, c_result) def status_2_db(id, status): '''把结果写入db''' conn = MySQLdb.connect(host=db_hostname, user=db_user, passwd=db_pass, db='url_mon',charset='utf8') cur = conn.cursor() sql_get_id_status = "select status_code from status_code where ID = %d and rep_point = '%s' ;" %(id, local_ip) cur.execute(sql_get_id_status) last_code = cur.fetchone() if last_code: last_code = last_code[0] cur_code = last_code * status + status sql_update_id_status = "update status_code set status_code = %d, rep_time = CURRENT_TIMESTAMP where ID = %d and rep_point = '%s';" %(cur_code, id, local_ip) cur.execute(sql_update_id_status) else: cur_code = status sql_into_id_status = "insert into status_code(ID, status_code, rep_point) value(%d, %d, '%s')" %(id, cur_code, local_ip) cur.execute(sql_into_id_status) conn.commit() conn.close() def main(): conn = MySQLdb.connect(host=db_hostname, user=db_user, passwd='test', db='url_mon',charset='utf8') cur = conn.cursor() cur.execute("select * from montior_url;") while True: line = cur.fetchone() if not line: break c_id, c_domain, c_location, c_method, c_keyword = line[0], line[1], line[
ine[3], line[4] c_url = "http://%s%s" % (c_domain,c_location) if c_method == line[5]: c_post_d = line[6] Process(target=check_url, args=(c_id, c_url, c_keyword)).start() ###变量获取区域 local_ip = get_localIP() cf = ConfigParser.ConfigParser() cf.read("./local_config") db_hostname = get_args("DB", "db_host") db_user = get_args("DB", "username") db_pass = get_args("DB", "passwd") db_default = get_args("DB", "db") if __name__ == "__main__": main()
2], l
conditional_block
outroTipoDeProducaoBibliografica.py
#!/usr/bin/python # encoding: utf-8 # filename: outroTipoDeProducaoBibliografica.py # # scriptLattes V8 # Copyright 2005-2013: Jesús P. Mena-Chalco e Roberto M. Cesar-Jr. # http://scriptlattes.sourceforge.net/ # # # Este programa é um software livre; você pode redistribui-lo e/ou # modifica-lo dentro dos termos da Licença Pública Geral GNU como # publicada pela Fundação do Software Livre (FSF); na versão 2 da # Licença, ou (na sua opinião) qualquer versão. # # Este programa é distribuído na esperança que possa ser util, # mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer # MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a # Licença Pública Geral GNU para maiores detalhes. # # Você deve ter recebido uma cópia da Licença Pública Geral GNU # junto com este programa, se não, escreva para a Fundação do Software # Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # from scriptLattes import * from geradorDePaginasWeb import * import re class OutroTipoDeProducaoBibliografica: item = None # dado bruto idMembro = None relevante = None autores = None titulo = None ano = None natureza = None # tipo de producao chave = None def __init__(self, idMembro, pa
em='', relevante=''): self.idMembro = set([]) self.idMembro.add(idMembro) if not partesDoItem=='': # partesDoItem[0]: Numero (NAO USADO) # partesDoItem[1]: Descricao do livro (DADO BRUTO) self.relevante = relevante self.item = partesDoItem[1] # Dividir o item na suas partes constituintes partes = self.item.partition(" . ") self.autores = partes[0].strip() partes = partes[2] aux = re.findall(u' \((.*?)\)\.$', partes) if len(aux)>0: self.natureza = aux[-1] partes = partes.rpartition(" (") partes = partes[0] else: self.natureza = '' aux = re.findall(u' ((?:19|20)\d\d)\\b', partes) if len(aux)>0: self.ano = aux[-1] #.strip().rstrip(".").rstrip(",") partes = partes.rpartition(" ") partes = partes[0] else: self.ano = '' self.titulo = partes.strip().rstrip(".").rstrip(",") self.chave = self.autores # chave de comparação entre os objetos else: self.relevante = '' self.autores = '' self.titulo = '' self.ano = '' self.natureza = '' def compararCom(self, objeto): if self.idMembro.isdisjoint(objeto.idMembro) and compararCadeias(self.titulo, objeto.titulo): # Os IDs dos membros são agrupados. # Essa parte é importante para a criação do GRAFO de colaborações self.idMembro.update(objeto.idMembro) if len(self.autores)<len(objeto.autores): self.autores = objeto.autores if len(self.titulo)<len(objeto.titulo): self.titulo = objeto.titulo if len(self.natureza)<len(objeto.natureza): self.natureza = objeto.natureza return self else: # nao similares return None def html(self, listaDeMembros): s = self.autores + '. <b>' + self.titulo + '</b>. ' s+= str(self.ano) + '. ' if str(self.ano).isdigit() else '. ' s+= self.natureza if not self.natureza=='' else '' s+= menuHTMLdeBuscaPB(self.titulo) return s # ------------------------------------------------------------------------ # def __str__(self): s = "\n[OUTRO TIPO DE PRODUCAO BIBLIOGRAFICA] \n" s += "+ID-MEMBRO : " + str(self.idMembro) + "\n" s += "+RELEVANTE : " + str(self.relevante) + "\n" s += "+AUTORES : " + self.autores.encode('utf8','replace') + "\n" s += "+TITULO : " + self.titulo.encode('utf8','replace') + "\n" s += "+ANO : " + str(self.ano) + "\n" s += "+NATUREZA : " + self.natureza.encode('utf8','replace') + "\n" s += "+item : " + self.item.encode('utf8','replace') + "\n" return s
rtesDoIt
identifier_name
outroTipoDeProducaoBibliografica.py
#!/usr/bin/python # encoding: utf-8 # filename: outroTipoDeProducaoBibliografica.py # # scriptLattes V8 # Copyright 2005-2013: Jesús P. Mena-Chalco e Roberto M. Cesar-Jr. # http://scriptlattes.sourceforge.net/ # # # Este programa é um software livre; você pode redistribui-lo e/ou # modifica-lo dentro dos termos da Licença Pública Geral GNU como # publicada pela Fundação do Software Livre (FSF); na versão 2 da # Licença, ou (na sua opinião) qualquer versão. # # Este programa é distribuído na esperança que possa ser util, # mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer # MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a # Licença Pública Geral GNU para maiores detalhes. # # Você deve ter recebido uma cópia da Licença Pública Geral GNU # junto com este programa, se não, escreva para a Fundação do Software # Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # from scriptLattes import * from geradorDePaginasWeb import * import re class OutroTipoDeProducaoBibliografica: item = None # dado bruto idMembro = None relevante = None autores = None titulo = None ano = None natureza = None # tipo de producao chave = None def __init__(self, idMembro, partesDoItem='', relevante=''): self.idMembro = set([]) self.idMembro.add(idMembro) if not partesDoItem=='': # partesDoItem[0]: Numero (NAO USADO) # partesDoItem[1]: Descricao do livro (DADO BRUTO) self.relevante = relevante self.item = partesDoItem[1] # Dividir o item na suas partes constituintes partes = self.item.partition(" . ") self.autores = partes[0].strip() partes = partes[2] aux = re.findall(u' \((.*?)\)\.$', partes) if len(aux)>0: self.natureza = aux[-1] partes = partes.rpartition(" (") partes = partes[0] else: self.natureza = '' aux = re.findall(u' ((?:19|20)\d\d)\\b', partes) if len(aux)>0: self.ano = aux[-1] #.strip().rstrip(".").rstrip(",") partes = partes.rpartition(" ") partes = partes[0] else: self.ano = '' self.titulo = partes.strip().rstrip(".").rstrip(",") self.chave = self.autores # chave de comparação entre os objetos else: self.relevante = '' self.autores = '' self.titulo = '' self.ano = '' self.natureza = '' def compararCom(self, objeto): if self.idMembro.isdisjoint(objeto.idMembro) and compararCadeias(self.titulo, objeto.titulo): # Os IDs dos membros são agrupados. # Essa parte é importante para a criação do GRAFO de colaborações self.idMembro.update(objeto.idMembro) if len(self.autores)<len(objeto.autores): self.autores = objeto.autores
if len(self.titulo)<len(objeto.titulo): self.titulo = objeto.titulo if len(self.natureza)<len(objeto.natureza): self.natureza = objeto.natureza return self else: # nao similares return None def html(self, listaDeMembros): s = self.autores + '. <b>' + self.titulo + '</b>. ' s+= str(self.ano) + '. ' if str(self.ano).isdigit() else '. ' s+= self.natureza if not self.natureza=='' else '' s+= menuHTMLdeBuscaPB(self.titulo) return s # ------------------------------------------------------------------------ # def __str__(self): s = "\n[OUTRO TIPO DE PRODUCAO BIBLIOGRAFICA] \n" s += "+ID-MEMBRO : " + str(self.idMembro) + "\n" s += "+RELEVANTE : " + str(self.relevante) + "\n" s += "+AUTORES : " + self.autores.encode('utf8','replace') + "\n" s += "+TITULO : " + self.titulo.encode('utf8','replace') + "\n" s += "+ANO : " + str(self.ano) + "\n" s += "+NATUREZA : " + self.natureza.encode('utf8','replace') + "\n" s += "+item : " + self.item.encode('utf8','replace') + "\n" return s
random_line_split
outroTipoDeProducaoBibliografica.py
#!/usr/bin/python # encoding: utf-8 # filename: outroTipoDeProducaoBibliografica.py # # scriptLattes V8 # Copyright 2005-2013: Jesús P. Mena-Chalco e Roberto M. Cesar-Jr. # http://scriptlattes.sourceforge.net/ # # # Este programa é um software livre; você pode redistribui-lo e/ou # modifica-lo dentro dos termos da Licença Pública Geral GNU como # publicada pela Fundação do Software Livre (FSF); na versão 2 da # Licença, ou (na sua opinião) qualquer versão. # # Este programa é distribuído na esperança que possa ser util, # mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer # MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a # Licença Pública Geral GNU para maiores detalhes. # # Você deve ter recebido uma cópia da Licença Pública Geral GNU # junto com este programa, se não, escreva para a Fundação do Software # Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # from scriptLattes import * from geradorDePaginasWeb import * import re class OutroTipoDeProducaoBibliografica: item = None # dado bruto idMembro = None relevante = None autores = None titulo = None ano = None natureza = None # tipo de producao chave = None def __init__(self, idMembro, partesDoItem='', relevante=''): self.idMembro = set([]) self.idMembro.add(idMembro) if not partesDoItem=='': # partesDoItem[0]: Numero (NAO USADO) # partesDoItem[1]: Descricao do livro (DADO BRUTO) self.relevante = relevante self.item = partesDoItem[1] # Dividir o item na suas partes constituintes partes = self.item.partition(" . ") self.autores = partes[0].strip() partes = partes[2] aux = re.findall(u' \((.*?)\)\.$', partes) if len(aux)>0: self.natureza = aux[-1] partes = partes.rpartition(" (") partes = partes[0] else: self.natureza = '' aux = re.findall(u' ((?:19|20)\d\d)\\b', partes) if len(aux)>0: self.ano = aux[-1] #.strip().rstrip(".").rstrip(",") partes = partes.rpartition(" ") partes = partes[0] else: self.ano = '' self.titulo = partes.strip().rstrip(".").rstrip(",") self.chave = self.autores # chave de comparação entre os objetos else: self.relevante = '' self.autores = '' self.titulo = '' self.ano = '' self.natureza = '' def compararCom(self, objeto): if self.idMembro.isdisjoint(o
s = self.autores + '. <b>' + self.titulo + '</b>. ' s+= str(self.ano) + '. ' if str(self.ano).isdigit() else '. ' s+= self.natureza if not self.natureza=='' else '' s+= menuHTMLdeBuscaPB(self.titulo) return s # ------------------------------------------------------------------------ # def __str__(self): s = "\n[OUTRO TIPO DE PRODUCAO BIBLIOGRAFICA] \n" s += "+ID-MEMBRO : " + str(self.idMembro) + "\n" s += "+RELEVANTE : " + str(self.relevante) + "\n" s += "+AUTORES : " + self.autores.encode('utf8','replace') + "\n" s += "+TITULO : " + self.titulo.encode('utf8','replace') + "\n" s += "+ANO : " + str(self.ano) + "\n" s += "+NATUREZA : " + self.natureza.encode('utf8','replace') + "\n" s += "+item : " + self.item.encode('utf8','replace') + "\n" return s
bjeto.idMembro) and compararCadeias(self.titulo, objeto.titulo): # Os IDs dos membros são agrupados. # Essa parte é importante para a criação do GRAFO de colaborações self.idMembro.update(objeto.idMembro) if len(self.autores)<len(objeto.autores): self.autores = objeto.autores if len(self.titulo)<len(objeto.titulo): self.titulo = objeto.titulo if len(self.natureza)<len(objeto.natureza): self.natureza = objeto.natureza return self else: # nao similares return None def html(self, listaDeMembros):
identifier_body
outroTipoDeProducaoBibliografica.py
#!/usr/bin/python # encoding: utf-8 # filename: outroTipoDeProducaoBibliografica.py # # scriptLattes V8 # Copyright 2005-2013: Jesús P. Mena-Chalco e Roberto M. Cesar-Jr. # http://scriptlattes.sourceforge.net/ # # # Este programa é um software livre; você pode redistribui-lo e/ou # modifica-lo dentro dos termos da Licença Pública Geral GNU como # publicada pela Fundação do Software Livre (FSF); na versão 2 da # Licença, ou (na sua opinião) qualquer versão. # # Este programa é distribuído na esperança que possa ser util, # mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer # MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a # Licença Pública Geral GNU para maiores detalhes. # # Você deve ter recebido uma cópia da Licença Pública Geral GNU # junto com este programa, se não, escreva para a Fundação do Software # Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # from scriptLattes import * from geradorDePaginasWeb import * import re class OutroTipoDeProducaoBibliografica: item = None # dado bruto idMembro = None relevante = None autores = None titulo = None ano = None natureza = None # tipo de producao chave = None def __init__(self, idMembro, partesDoItem='', relevante=''): self.idMembro = set([]) self.idMembro.add(idMembro) if not partesDoItem=='': # partesDoItem[0]: Numero (NAO USADO) # partesDoItem[1]: Descricao do livro (DADO BRUTO) self.relevante = relevante self.item = partesDoItem[1] # Dividir o item na suas partes constituintes partes = self.item.partition(" . ") self.autores = partes[0].strip() partes = partes[2] aux = re.findall(u' \((.*?)\)\.$', partes) if len(aux)>0: self.natureza = aux[-1] partes = partes.rpartition(" (") partes = partes[0] else: self.natureza = '' aux = re.findall(u' ((?:19|20)\d\d)\\b', partes) if len(aux)>0: self.ano = aux[-1] #.strip().rstrip(".").rstrip(",") partes = partes.rpartition(" ") partes = partes[0] else: self.ano = '' self.titulo = partes.strip().rstrip(".").rstrip(",") self.chave = self.autores # chave de comparação entre os objetos else: self.relevante = '' self.autores = '' self.titulo = '' self.ano = '' self.natureza = '' def compararCom(self, objeto): if self.idMembro.isdisjoint(objeto.idMembro) and compararCadeias(self.titulo, objeto.titulo): # Os IDs dos membros são agrupados. # Essa parte é importante para a criação do GRAFO de colaborações self.idMembro.update(objeto.idMembro) if len(self.autores)<len(objeto.autores): self.autores = objeto.autores if len(self.titulo)<len(objeto.titulo): self.titulo = objeto.titulo if len(self.natureza)<len(objeto.natureza): self.natureza = objeto.natureza
lares return None def html(self, listaDeMembros): s = self.autores + '. <b>' + self.titulo + '</b>. ' s+= str(self.ano) + '. ' if str(self.ano).isdigit() else '. ' s+= self.natureza if not self.natureza=='' else '' s+= menuHTMLdeBuscaPB(self.titulo) return s # ------------------------------------------------------------------------ # def __str__(self): s = "\n[OUTRO TIPO DE PRODUCAO BIBLIOGRAFICA] \n" s += "+ID-MEMBRO : " + str(self.idMembro) + "\n" s += "+RELEVANTE : " + str(self.relevante) + "\n" s += "+AUTORES : " + self.autores.encode('utf8','replace') + "\n" s += "+TITULO : " + self.titulo.encode('utf8','replace') + "\n" s += "+ANO : " + str(self.ano) + "\n" s += "+NATUREZA : " + self.natureza.encode('utf8','replace') + "\n" s += "+item : " + self.item.encode('utf8','replace') + "\n" return s
return self else: # nao simi
conditional_block
__openerp__.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar) # All Rights Reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Multi Store', 'version': '8.0.1.0.0', 'category': 'Accounting', 'sequence': 14, 'summary': '', 'description': """ Multi Store =========== The main purpose of this module is to restrict journals access for users on different stores. This module add a new concept "stores" in some point similar to multicompany. Similar to multicompany: * User can have multiple stores available (store_ids) * User can be active only in one store (store_id) which can be set up in his own preferences * There is a group "multi store" that gives users the availability to see multi store fields
* If store_id is set, then journal can be seen by users on that store and parent stores It also restrict edition, creation and unlink on: account.move, account.invoice and account.voucher. It is done with the same logic to journal. We do not limitate the "read" of this models because user should need to access those documents, for example, to see partner due. """, 'author': 'ADHOC SA', 'website': 'www.adhoc.com.ar', 'license': 'AGPL-3', 'images': [ ], 'depends': [ 'account_voucher', ], 'data': [ 'views/res_store_view.xml', 'views/res_users_view.xml', 'views/account_view.xml', 'security/multi_store_security.xml', 'security/ir.model.access.csv', ], 'demo': [ ], 'test': [ ], 'installable': True, 'auto_install': False, 'application': False, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
This module also adds a store_id field on journal: * If store_id = False then journal can be seen by everyone
random_line_split
list-servers.controller.ts
/* * Copyright (c) 2015-2017 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation */ 'use strict'; import {IEnvironmentManagerMachineServer} from '../../../../../components/api/environment/environment-manager-machine'; import {ConfirmDialogService} from '../../../../../components/service/confirm-dialog/confirm-dialog.service'; interface IServerListItem extends IEnvironmentManagerMachineServer { reference: string; } /** * @ngdoc controller * @name workspace.details.controller:ListServersController * @description This class is handling the controller for list of servers * @author Oleksii Kurinnyi */ export class ListServersController { $mdDialog: ng.material.IDialogService; lodash: _.LoDashStatic; isNoSelected: boolean = true; isBulkChecked: boolean = false; serversSelectedStatus: { [serverName: string]: boolean } = {}; serversSelectedNumber: number = 0; serversOrderBy: string = 'reference'; server: IEnvironmentManagerMachineServer; servers: { [reference: string]: IEnvironmentManagerMachineServer }; serversList: IServerListItem[]; serversOnChange: Function; private confirmDialogService: ConfirmDialogService; /** * Default constructor that is using resource * @ngInject for Dependency injection */ constructor($mdDialog: ng.material.IDialogService, lodash: _.LoDashStatic, confirmDialogService: ConfirmDialogService) { this.$mdDialog = $mdDialog; this.lodash = lodash; this.confirmDialogService = confirmDialogService; this.buildServersList(); } /** * Build list of servers */ buildServersList(): void { this.serversList = this.lodash.map(this.servers, (server: IEnvironmentManagerMachineServer, reference: string) => { let serverItem: IServerListItem = angular.extend({}, {reference: reference}, server); serverItem.protocol = serverItem.protocol ? serverItem.protocol : 'http'; return serverItem; }); } /** * Update server selected status */ updateSelectedStatus(): void { this.serversSelectedNumber = 0; this.isBulkChecked = !!this.serversList.length; this.serversList.forEach((serverListItem: IServerListItem) => { if (this.serversSelectedStatus[serverListItem.reference]) { this.serversSelectedNumber++; } else { this.isBulkChecked = false; } }); } /** * @param {string} name */ changeServerSelection(name: string): void { this.serversSelectedStatus[name] = !this.serversSelectedStatus[name]; this.updateSelectedStatus(); } /** * Change bulk selection value */ changeBulkSelection(): void { if (this.isBulkChecked) { this.deselectAllServers(); this.isBulkChecked = false; return; } this.selectAllServers(); this.isBulkChecked = true; } /** * Check all servers in list */ selectAllServers(): void { this.serversSelectedNumber = 0; this.serversList.forEach((serverListItem: IServerListItem) => { if (serverListItem.userScope === false) { return; } this.serversSelectedNumber++; this.serversSelectedStatus[serverListItem.reference] = true; }); } /** * Uncheck all servers in list */ deselectAllServers(): void { this.serversSelectedStatus = {}; this.serversSelectedNumber = 0; } /** * Add new server. * * @param {string} reference * @param {number} port * @param {string} protocol */ addServer(reference: string, port: number, protocol: string): void { this.servers[reference] = { port: port, protocol: protocol, userScope: true }; this.updateSelectedStatus(); this.serversOnChange(); this.buildServersList(); } /** * Update server * * @param {string} oldReference * @param {string} newReference * @param {number} port * @param {string} protocol */ updateServer(oldReference: string, newReference: string, port: number, protocol: string): void { delete this.servers[oldReference]; this.addServer(newReference, port, protocol); } /** * Show dialog to add new or edit existing server * * @param {MouseEvent} $event * @param {string=} reference */ showEditDialog($event: MouseEvent, reference?: string): void { this.$mdDialog.show({ targetEvent: $event, controller: 'EditServerDialogController', controllerAs: 'editServerDialogController', bindToController: true, clickOutsideToClose: true, locals: { toEdit: reference, servers: this.servers, callbackController: this }, templateUrl: 'app/workspaces/workspace-details/environments/list-servers/edit-server-dialog/edit-server-dialog.html' }); } /** * Removes selected servers */
(): void { this.showDeleteConfirmation(this.serversSelectedNumber).then(() => { this.lodash.forEach(this.serversSelectedStatus, (server: IEnvironmentManagerMachineServer, name: string) => { delete this.servers[name]; }); this.deselectAllServers(); this.isBulkChecked = false; this.serversOnChange(); this.buildServersList(); }); } /** * Show confirmation popup before server to delete * @param {number} numberToDelete * @returns {angular.IPromise<any>} */ showDeleteConfirmation(numberToDelete: number): ng.IPromise<any> { let content = 'Would you like to delete '; if (numberToDelete > 1) { content += 'these ' + numberToDelete + ' servers?'; } else { content += 'this selected server?'; } return this.confirmDialogService.showConfirmDialog('Remove servers', content, 'Delete'); } }
deleteSelectedServers
identifier_name
list-servers.controller.ts
/* * Copyright (c) 2015-2017 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation */ 'use strict'; import {IEnvironmentManagerMachineServer} from '../../../../../components/api/environment/environment-manager-machine'; import {ConfirmDialogService} from '../../../../../components/service/confirm-dialog/confirm-dialog.service'; interface IServerListItem extends IEnvironmentManagerMachineServer { reference: string; } /** * @ngdoc controller * @name workspace.details.controller:ListServersController * @description This class is handling the controller for list of servers * @author Oleksii Kurinnyi */ export class ListServersController { $mdDialog: ng.material.IDialogService; lodash: _.LoDashStatic; isNoSelected: boolean = true; isBulkChecked: boolean = false; serversSelectedStatus: { [serverName: string]: boolean } = {}; serversSelectedNumber: number = 0; serversOrderBy: string = 'reference'; server: IEnvironmentManagerMachineServer; servers: { [reference: string]: IEnvironmentManagerMachineServer }; serversList: IServerListItem[]; serversOnChange: Function; private confirmDialogService: ConfirmDialogService; /** * Default constructor that is using resource * @ngInject for Dependency injection */ constructor($mdDialog: ng.material.IDialogService, lodash: _.LoDashStatic, confirmDialogService: ConfirmDialogService) { this.$mdDialog = $mdDialog; this.lodash = lodash; this.confirmDialogService = confirmDialogService; this.buildServersList(); } /** * Build list of servers */ buildServersList(): void { this.serversList = this.lodash.map(this.servers, (server: IEnvironmentManagerMachineServer, reference: string) => { let serverItem: IServerListItem = angular.extend({}, {reference: reference}, server); serverItem.protocol = serverItem.protocol ? serverItem.protocol : 'http'; return serverItem; }); } /** * Update server selected status */ updateSelectedStatus(): void { this.serversSelectedNumber = 0; this.isBulkChecked = !!this.serversList.length; this.serversList.forEach((serverListItem: IServerListItem) => { if (this.serversSelectedStatus[serverListItem.reference]) { this.serversSelectedNumber++; } else
}); } /** * @param {string} name */ changeServerSelection(name: string): void { this.serversSelectedStatus[name] = !this.serversSelectedStatus[name]; this.updateSelectedStatus(); } /** * Change bulk selection value */ changeBulkSelection(): void { if (this.isBulkChecked) { this.deselectAllServers(); this.isBulkChecked = false; return; } this.selectAllServers(); this.isBulkChecked = true; } /** * Check all servers in list */ selectAllServers(): void { this.serversSelectedNumber = 0; this.serversList.forEach((serverListItem: IServerListItem) => { if (serverListItem.userScope === false) { return; } this.serversSelectedNumber++; this.serversSelectedStatus[serverListItem.reference] = true; }); } /** * Uncheck all servers in list */ deselectAllServers(): void { this.serversSelectedStatus = {}; this.serversSelectedNumber = 0; } /** * Add new server. * * @param {string} reference * @param {number} port * @param {string} protocol */ addServer(reference: string, port: number, protocol: string): void { this.servers[reference] = { port: port, protocol: protocol, userScope: true }; this.updateSelectedStatus(); this.serversOnChange(); this.buildServersList(); } /** * Update server * * @param {string} oldReference * @param {string} newReference * @param {number} port * @param {string} protocol */ updateServer(oldReference: string, newReference: string, port: number, protocol: string): void { delete this.servers[oldReference]; this.addServer(newReference, port, protocol); } /** * Show dialog to add new or edit existing server * * @param {MouseEvent} $event * @param {string=} reference */ showEditDialog($event: MouseEvent, reference?: string): void { this.$mdDialog.show({ targetEvent: $event, controller: 'EditServerDialogController', controllerAs: 'editServerDialogController', bindToController: true, clickOutsideToClose: true, locals: { toEdit: reference, servers: this.servers, callbackController: this }, templateUrl: 'app/workspaces/workspace-details/environments/list-servers/edit-server-dialog/edit-server-dialog.html' }); } /** * Removes selected servers */ deleteSelectedServers(): void { this.showDeleteConfirmation(this.serversSelectedNumber).then(() => { this.lodash.forEach(this.serversSelectedStatus, (server: IEnvironmentManagerMachineServer, name: string) => { delete this.servers[name]; }); this.deselectAllServers(); this.isBulkChecked = false; this.serversOnChange(); this.buildServersList(); }); } /** * Show confirmation popup before server to delete * @param {number} numberToDelete * @returns {angular.IPromise<any>} */ showDeleteConfirmation(numberToDelete: number): ng.IPromise<any> { let content = 'Would you like to delete '; if (numberToDelete > 1) { content += 'these ' + numberToDelete + ' servers?'; } else { content += 'this selected server?'; } return this.confirmDialogService.showConfirmDialog('Remove servers', content, 'Delete'); } }
{ this.isBulkChecked = false; }
conditional_block
list-servers.controller.ts
/* * Copyright (c) 2015-2017 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation */ 'use strict'; import {IEnvironmentManagerMachineServer} from '../../../../../components/api/environment/environment-manager-machine'; import {ConfirmDialogService} from '../../../../../components/service/confirm-dialog/confirm-dialog.service'; interface IServerListItem extends IEnvironmentManagerMachineServer { reference: string; } /** * @ngdoc controller * @name workspace.details.controller:ListServersController * @description This class is handling the controller for list of servers * @author Oleksii Kurinnyi */ export class ListServersController { $mdDialog: ng.material.IDialogService; lodash: _.LoDashStatic; isNoSelected: boolean = true; isBulkChecked: boolean = false; serversSelectedStatus: { [serverName: string]: boolean } = {}; serversSelectedNumber: number = 0; serversOrderBy: string = 'reference'; server: IEnvironmentManagerMachineServer; servers: { [reference: string]: IEnvironmentManagerMachineServer }; serversList: IServerListItem[]; serversOnChange: Function; private confirmDialogService: ConfirmDialogService; /** * Default constructor that is using resource * @ngInject for Dependency injection */ constructor($mdDialog: ng.material.IDialogService, lodash: _.LoDashStatic, confirmDialogService: ConfirmDialogService) { this.$mdDialog = $mdDialog; this.lodash = lodash; this.confirmDialogService = confirmDialogService; this.buildServersList(); } /** * Build list of servers */ buildServersList(): void { this.serversList = this.lodash.map(this.servers, (server: IEnvironmentManagerMachineServer, reference: string) => { let serverItem: IServerListItem = angular.extend({}, {reference: reference}, server); serverItem.protocol = serverItem.protocol ? serverItem.protocol : 'http'; return serverItem; }); } /** * Update server selected status */ updateSelectedStatus(): void { this.serversSelectedNumber = 0; this.isBulkChecked = !!this.serversList.length; this.serversList.forEach((serverListItem: IServerListItem) => { if (this.serversSelectedStatus[serverListItem.reference]) { this.serversSelectedNumber++; } else { this.isBulkChecked = false; } }); } /** * @param {string} name */ changeServerSelection(name: string): void { this.serversSelectedStatus[name] = !this.serversSelectedStatus[name]; this.updateSelectedStatus(); } /** * Change bulk selection value */ changeBulkSelection(): void { if (this.isBulkChecked) { this.deselectAllServers(); this.isBulkChecked = false; return; } this.selectAllServers(); this.isBulkChecked = true; } /** * Check all servers in list */ selectAllServers(): void { this.serversSelectedNumber = 0; this.serversList.forEach((serverListItem: IServerListItem) => { if (serverListItem.userScope === false) { return; } this.serversSelectedNumber++; this.serversSelectedStatus[serverListItem.reference] = true; }); } /** * Uncheck all servers in list */ deselectAllServers(): void { this.serversSelectedStatus = {}; this.serversSelectedNumber = 0; } /** * Add new server. * * @param {string} reference * @param {number} port * @param {string} protocol */ addServer(reference: string, port: number, protocol: string): void { this.servers[reference] = { port: port, protocol: protocol, userScope: true }; this.updateSelectedStatus(); this.serversOnChange(); this.buildServersList(); } /** * Update server * * @param {string} oldReference * @param {string} newReference * @param {number} port * @param {string} protocol */ updateServer(oldReference: string, newReference: string, port: number, protocol: string): void { delete this.servers[oldReference]; this.addServer(newReference, port, protocol); } /** * Show dialog to add new or edit existing server * * @param {MouseEvent} $event * @param {string=} reference */ showEditDialog($event: MouseEvent, reference?: string): void { this.$mdDialog.show({ targetEvent: $event, controller: 'EditServerDialogController', controllerAs: 'editServerDialogController', bindToController: true, clickOutsideToClose: true, locals: { toEdit: reference, servers: this.servers, callbackController: this }, templateUrl: 'app/workspaces/workspace-details/environments/list-servers/edit-server-dialog/edit-server-dialog.html' }); } /** * Removes selected servers */ deleteSelectedServers(): void { this.showDeleteConfirmation(this.serversSelectedNumber).then(() => { this.lodash.forEach(this.serversSelectedStatus, (server: IEnvironmentManagerMachineServer, name: string) => { delete this.servers[name]; }); this.deselectAllServers(); this.isBulkChecked = false; this.serversOnChange(); this.buildServersList(); }); } /** * Show confirmation popup before server to delete * @param {number} numberToDelete * @returns {angular.IPromise<any>} */ showDeleteConfirmation(numberToDelete: number): ng.IPromise<any>
}
{ let content = 'Would you like to delete '; if (numberToDelete > 1) { content += 'these ' + numberToDelete + ' servers?'; } else { content += 'this selected server?'; } return this.confirmDialogService.showConfirmDialog('Remove servers', content, 'Delete'); }
identifier_body
list-servers.controller.ts
/* * Copyright (c) 2015-2017 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation */ 'use strict'; import {IEnvironmentManagerMachineServer} from '../../../../../components/api/environment/environment-manager-machine'; import {ConfirmDialogService} from '../../../../../components/service/confirm-dialog/confirm-dialog.service'; interface IServerListItem extends IEnvironmentManagerMachineServer { reference: string; } /** * @ngdoc controller * @name workspace.details.controller:ListServersController * @description This class is handling the controller for list of servers * @author Oleksii Kurinnyi */ export class ListServersController { $mdDialog: ng.material.IDialogService; lodash: _.LoDashStatic; isNoSelected: boolean = true; isBulkChecked: boolean = false; serversSelectedStatus: { [serverName: string]: boolean } = {}; serversSelectedNumber: number = 0; serversOrderBy: string = 'reference'; server: IEnvironmentManagerMachineServer; servers: { [reference: string]: IEnvironmentManagerMachineServer }; serversList: IServerListItem[]; serversOnChange: Function; private confirmDialogService: ConfirmDialogService; /** * Default constructor that is using resource * @ngInject for Dependency injection */ constructor($mdDialog: ng.material.IDialogService, lodash: _.LoDashStatic, confirmDialogService: ConfirmDialogService) { this.$mdDialog = $mdDialog; this.lodash = lodash; this.confirmDialogService = confirmDialogService; this.buildServersList(); } /** * Build list of servers */ buildServersList(): void { this.serversList = this.lodash.map(this.servers, (server: IEnvironmentManagerMachineServer, reference: string) => { let serverItem: IServerListItem = angular.extend({}, {reference: reference}, server); serverItem.protocol = serverItem.protocol ? serverItem.protocol : 'http'; return serverItem; }); } /** * Update server selected status */ updateSelectedStatus(): void { this.serversSelectedNumber = 0; this.isBulkChecked = !!this.serversList.length; this.serversList.forEach((serverListItem: IServerListItem) => { if (this.serversSelectedStatus[serverListItem.reference]) { this.serversSelectedNumber++; } else { this.isBulkChecked = false; } }); } /** * @param {string} name */ changeServerSelection(name: string): void { this.serversSelectedStatus[name] = !this.serversSelectedStatus[name]; this.updateSelectedStatus(); } /** * Change bulk selection value */ changeBulkSelection(): void { if (this.isBulkChecked) { this.deselectAllServers(); this.isBulkChecked = false; return; } this.selectAllServers(); this.isBulkChecked = true; } /** * Check all servers in list */ selectAllServers(): void { this.serversSelectedNumber = 0; this.serversList.forEach((serverListItem: IServerListItem) => { if (serverListItem.userScope === false) { return; } this.serversSelectedNumber++; this.serversSelectedStatus[serverListItem.reference] = true; }); } /** * Uncheck all servers in list */ deselectAllServers(): void { this.serversSelectedStatus = {}; this.serversSelectedNumber = 0; } /** * Add new server. *
*/ addServer(reference: string, port: number, protocol: string): void { this.servers[reference] = { port: port, protocol: protocol, userScope: true }; this.updateSelectedStatus(); this.serversOnChange(); this.buildServersList(); } /** * Update server * * @param {string} oldReference * @param {string} newReference * @param {number} port * @param {string} protocol */ updateServer(oldReference: string, newReference: string, port: number, protocol: string): void { delete this.servers[oldReference]; this.addServer(newReference, port, protocol); } /** * Show dialog to add new or edit existing server * * @param {MouseEvent} $event * @param {string=} reference */ showEditDialog($event: MouseEvent, reference?: string): void { this.$mdDialog.show({ targetEvent: $event, controller: 'EditServerDialogController', controllerAs: 'editServerDialogController', bindToController: true, clickOutsideToClose: true, locals: { toEdit: reference, servers: this.servers, callbackController: this }, templateUrl: 'app/workspaces/workspace-details/environments/list-servers/edit-server-dialog/edit-server-dialog.html' }); } /** * Removes selected servers */ deleteSelectedServers(): void { this.showDeleteConfirmation(this.serversSelectedNumber).then(() => { this.lodash.forEach(this.serversSelectedStatus, (server: IEnvironmentManagerMachineServer, name: string) => { delete this.servers[name]; }); this.deselectAllServers(); this.isBulkChecked = false; this.serversOnChange(); this.buildServersList(); }); } /** * Show confirmation popup before server to delete * @param {number} numberToDelete * @returns {angular.IPromise<any>} */ showDeleteConfirmation(numberToDelete: number): ng.IPromise<any> { let content = 'Would you like to delete '; if (numberToDelete > 1) { content += 'these ' + numberToDelete + ' servers?'; } else { content += 'this selected server?'; } return this.confirmDialogService.showConfirmDialog('Remove servers', content, 'Delete'); } }
* @param {string} reference * @param {number} port * @param {string} protocol
random_line_split
Vocabularies.js
import React, { PropTypes } from 'react' import SettingsList from './SettingsList' import { parseVocabulary } from '../../common/Vocabulary' export class Predictions extends React.Component { static propTypes = { token: PropTypes.string.isRequired, state: PropTypes.object.isRequired, actions: PropTypes.object.isRequired }; type = 'vocabularies'; addItem = (values) => { return parseVocabulary(values) .then((vocabulary) => { this.props.actions.addItem(this.props.token, this.type, vocabulary); }); }; deleteItem = (id, name) => { this.props.actions.deleteItem(this.props.token, this.type, id, name); }; editItem = (id, values) => { const { state, token, actions } = this.props; const item = state.items[id]; const isEditName = item.name !== values.name; return parseVocabulary(values) .then((vocabulary) => { if (isEditName) { actions.editItemName(token, this.type, id, vocabulary); } else { actions.editItem(token, this.type, id, vocabulary); } }); }; render() { let state = this.props.state; return ( <div> <SettingsList state={state} type={this.type}
/> </div> ) } } export default Predictions
actions={this.props.actions} onAddItem={this.addItem} onDeleteItem={this.deleteItem} onEditItem={this.editItem}
random_line_split
Vocabularies.js
import React, { PropTypes } from 'react' import SettingsList from './SettingsList' import { parseVocabulary } from '../../common/Vocabulary' export class Predictions extends React.Component { static propTypes = { token: PropTypes.string.isRequired, state: PropTypes.object.isRequired, actions: PropTypes.object.isRequired }; type = 'vocabularies'; addItem = (values) => { return parseVocabulary(values) .then((vocabulary) => { this.props.actions.addItem(this.props.token, this.type, vocabulary); }); }; deleteItem = (id, name) => { this.props.actions.deleteItem(this.props.token, this.type, id, name); }; editItem = (id, values) => { const { state, token, actions } = this.props; const item = state.items[id]; const isEditName = item.name !== values.name; return parseVocabulary(values) .then((vocabulary) => { if (isEditName)
else { actions.editItem(token, this.type, id, vocabulary); } }); }; render() { let state = this.props.state; return ( <div> <SettingsList state={state} type={this.type} actions={this.props.actions} onAddItem={this.addItem} onDeleteItem={this.deleteItem} onEditItem={this.editItem} /> </div> ) } } export default Predictions
{ actions.editItemName(token, this.type, id, vocabulary); }
conditional_block
Vocabularies.js
import React, { PropTypes } from 'react' import SettingsList from './SettingsList' import { parseVocabulary } from '../../common/Vocabulary' export class Predictions extends React.Component { static propTypes = { token: PropTypes.string.isRequired, state: PropTypes.object.isRequired, actions: PropTypes.object.isRequired }; type = 'vocabularies'; addItem = (values) => { return parseVocabulary(values) .then((vocabulary) => { this.props.actions.addItem(this.props.token, this.type, vocabulary); }); }; deleteItem = (id, name) => { this.props.actions.deleteItem(this.props.token, this.type, id, name); }; editItem = (id, values) => { const { state, token, actions } = this.props; const item = state.items[id]; const isEditName = item.name !== values.name; return parseVocabulary(values) .then((vocabulary) => { if (isEditName) { actions.editItemName(token, this.type, id, vocabulary); } else { actions.editItem(token, this.type, id, vocabulary); } }); }; render()
} export default Predictions
{ let state = this.props.state; return ( <div> <SettingsList state={state} type={this.type} actions={this.props.actions} onAddItem={this.addItem} onDeleteItem={this.deleteItem} onEditItem={this.editItem} /> </div> ) }
identifier_body
Vocabularies.js
import React, { PropTypes } from 'react' import SettingsList from './SettingsList' import { parseVocabulary } from '../../common/Vocabulary' export class
extends React.Component { static propTypes = { token: PropTypes.string.isRequired, state: PropTypes.object.isRequired, actions: PropTypes.object.isRequired }; type = 'vocabularies'; addItem = (values) => { return parseVocabulary(values) .then((vocabulary) => { this.props.actions.addItem(this.props.token, this.type, vocabulary); }); }; deleteItem = (id, name) => { this.props.actions.deleteItem(this.props.token, this.type, id, name); }; editItem = (id, values) => { const { state, token, actions } = this.props; const item = state.items[id]; const isEditName = item.name !== values.name; return parseVocabulary(values) .then((vocabulary) => { if (isEditName) { actions.editItemName(token, this.type, id, vocabulary); } else { actions.editItem(token, this.type, id, vocabulary); } }); }; render() { let state = this.props.state; return ( <div> <SettingsList state={state} type={this.type} actions={this.props.actions} onAddItem={this.addItem} onDeleteItem={this.deleteItem} onEditItem={this.editItem} /> </div> ) } } export default Predictions
Predictions
identifier_name
maps.module.ts
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { NgaModule } from '../../theme/nga.module'; import { routing } from './maps.routing'; import { Maps } from './maps.component'; import { BubbleMaps } from './components/bubbleMaps/bubbleMaps.component'; import { EsriMaps } from './components/esriMaps/esriMaps.component'; import { GoogleMaps } from './components/googleMaps/googleMaps.component'; import { LeafletMaps } from './components/leafletMaps/leafletMaps.component'; import { LineMaps } from './components/lineMaps/lineMaps.component'; import { BubbleMapsService } from './components/bubbleMaps/bubbleMaps.service'; import { LineMapsService } from './components/lineMaps/lineMaps.service'; @NgModule({ imports: [ CommonModule, FormsModule, NgaModule, routing ], declarations: [ Maps, BubbleMaps, EsriMaps, GoogleMaps, LeafletMaps, LineMaps ], providers: [ BubbleMapsService, LineMapsService ] }) export class
{}
MapsModule
identifier_name
maps.module.ts
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { NgaModule } from '../../theme/nga.module'; import { routing } from './maps.routing'; import { Maps } from './maps.component'; import { BubbleMaps } from './components/bubbleMaps/bubbleMaps.component'; import { EsriMaps } from './components/esriMaps/esriMaps.component'; import { GoogleMaps } from './components/googleMaps/googleMaps.component'; import { LeafletMaps } from './components/leafletMaps/leafletMaps.component'; import { LineMaps } from './components/lineMaps/lineMaps.component'; import { BubbleMapsService } from './components/bubbleMaps/bubbleMaps.service'; import { LineMapsService } from './components/lineMaps/lineMaps.service';
NgaModule, routing ], declarations: [ Maps, BubbleMaps, EsriMaps, GoogleMaps, LeafletMaps, LineMaps ], providers: [ BubbleMapsService, LineMapsService ] }) export class MapsModule {}
@NgModule({ imports: [ CommonModule, FormsModule,
random_line_split
contact-form.component.ts
import { Component, OnInit, OnDestroy, Input, Output, EventEmitter } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { AlertsService } from '@jaspero/ng2-alerts'; import { AppStateService } from '../../../services/app-state.service'; import { ApiClient, Contact, Address, UpdateContactRequest, LookupEntry, Country } from '../../../services/incontrl-apiclient'; import { FormControl } from '@angular/forms'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/startWith'; import 'rxjs/add/operator/map'; import { LookupsService } from '../../../services/lookups.service'; @Component({ selector: 'app-contact-form', templateUrl: './contact-form.component.html', styleUrls: ['../forms.components.scss'] }) export class ContactFormComponent implements OnInit, OnDestroy { countryCtrl: FormControl; filteredCountries: Observable<any[]>; subscription_key: any = null; subscription_id: any = null; private _bak: any = null; private _model: any = null; public readonly = true; private busy = false; public countries = []; params_sub: any = null; myControl: FormControl = new FormControl(); @Output() model_changed: EventEmitter<any> = new EventEmitter<any>(); @Input() public set model(value: Contact) { this._model = value; } public get
(): Contact { return this._model; } constructor(private alertsService: AlertsService, private route: ActivatedRoute, private appState: AppStateService, private apiClient: ApiClient, private lookups: LookupsService) { this.model = new Contact(); this.model.address = new Address(); this.countryCtrl = new FormControl(); this.filteredCountries = this.countryCtrl.valueChanges .startWith(null) .map(country => country ? this.filterCountries(country) : this.countries.slice()); } filterCountries(name: string) { return this.countries.filter(country => country.description.toLowerCase().indexOf(name.toLowerCase()) === 0); } ngOnInit() { this.lookups.countries.subscribe((items) => { this.countries = items; }); this.params_sub = this.route.parent.params.subscribe((params) => { this.subscription_key = params['subscription-alias']; this.appState.getSubscriptionByKey(this.subscription_key) .subscribe((sub) => { this.subscription_id = sub.id; const contact = sub.data.contact.clone(); if (null == contact.address) { contact.address = new Address(); } this.model = contact; }); }); } ngOnDestroy() { this.params_sub.unsubscribe(); } toggle_edit_mode() { this.readonly = !this.readonly; if (!this.readonly) { this.bak(this.model); } } private bak(value: any) { this._bak = value.clone(); } cancel() { this.readonly = true; this.model = this._bak; } displayCountryFn(country: LookupEntry): string { return country ? country.description : ''; } save() { this.readonly = true; const request: UpdateContactRequest = new UpdateContactRequest(); request.firstName = this.model.firstName; request.lastName = this.model.lastName; request.email = this.model.email; request.phone1 = this.model.phone1; request.phone2 = this.model.phone2; request.skype = this.model.skype; request.notes = this.model.notes; request.address = this.model.address; this.apiClient.updateSubscriptionContact(this.subscription_id, request).subscribe((company) => { // create a new backup copy this.bak(this.model); this.appState.getSubscriptionByKey(this.subscription_key).subscribe((sub) => { sub.data.contact = this.model; this.alertsService.create('success', 'Η αποθήκευση των αλλαγών σας έγινε με επιτυχία!'); }); }, (error) => { console.log(error); this.alertsService.create('error', 'Σφάλμα κατα την αποθήκευση! Μύνημα συστήματος: ' + error); // keep on editing... this.readonly = false; }); } }
model
identifier_name