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
filters.tsx
import * as React from 'react'; import { AppliedFilter, DataTypes, GridFilters, numberWithCommas, ReactPowerTable, withInternalPaging, withInternalSorting } from '../../src/'; import { defaultColumns, partyList, sampledata } from './shared'; // //if coming in from DTO // const availDTO = [ // { fieldName: 'number', dataType: 'int' }, // { fieldName: 'president', dataType: 'string' }, // { fieldName: 'birth_year', dataType: 'int' }, // { fieldName: 'death_year', dataType: 'int', canBeNull: true }, // { fieldName: 'took_office', dataType: 'date' }, // { fieldName: 'left_office', dataType: 'date', canBeNull: true },
// const availableFiltersMap = createKeyedMap(availDTO.map(m => new DataTypes[m.dataType](m)), m=>m.fieldName); //availableFilters.party = new DataTypes.list(availableFilters.party, partyList); const partyListOptions = partyList.map(m => ({ label: m.label, value: m.label })); //if building in JS const availableFilters = [ new DataTypes.int('number'), new DataTypes.string('president'), new DataTypes.int('birth_year'), new DataTypes.decimal({ fieldName: 'death_year', canBeNull: true }), new DataTypes.date({ fieldName: 'took_office' }), new DataTypes.date({ fieldName: 'left_office', canBeNull: true }), new DataTypes.list('party', partyListOptions), new DataTypes.boolean({ fieldName: 'assasinated', displayName: 'was assasinated' }), new DataTypes.timespan({ fieldName: 'timeBorn', displayName: 'time born' }), ]; //const columns = [...defaultColumns, { field: m => m.timeBorn, width: 80, formatter: formatTimeValue }]; const assasinatedPresidents = [16, 20, 25, 35]; function padStart(str: string, targetLength: number, padString: string) { // tslint:disable-next-line:no-bitwise targetLength = targetLength >> 0; //truncate if number, or convert non-number to 0; padString = String(typeof padString !== 'undefined' ? padString : ' '); if (str.length >= targetLength) { return String(str); } else { targetLength = targetLength - str.length; if (targetLength > padString.length) { padString += padString.repeat(targetLength / padString.length); //append to original to ensure we are longer than needed } return padString.slice(0, targetLength) + str; } } const data = sampledata.map(m => ({ ...m, assasinated: assasinatedPresidents.indexOf(m.number) > -1, timeBorn: padStart(Math.floor((Math.random() * 24)).toString(), 2, '0') + ':00' })); //const availableFiltersMap = createKeyedMap(availableFilters, m => m.fieldName); //availableFiltersMap.number.operations.gt.displayName = 'greater than TEST'; availableFilters.find(m => m.fieldName === 'death_year').operations['null'].displayName = 'still alive'; interface FiltersExampleState { appliedFilters: Array<AppliedFilter<any>>; } const Table = withInternalSorting(withInternalPaging(ReactPowerTable)); export class FiltersExample extends React.Component<never, FiltersExampleState> { constructor(props: never) { super(props); this.state = { appliedFilters: [] }; this.handleFiltersChange = this.handleFiltersChange.bind(this); } handleFiltersChange(newFilters: Array<AppliedFilter<any>>) { console.log('onFiltersChange', newFilters); this.setState({ appliedFilters: newFilters }); } render() { let filteredData = data; this.state.appliedFilters.forEach(m => { filteredData = m.filter.applyFilter(filteredData, m.operation, m.value); }); return ( <div className="row"> <div className="col-md-3"> <div className="grid-filters"> <div className="small"> {numberWithCommas(filteredData.length) + ' Presidents'} &nbsp; </div> <div style={{ marginTop: 10 }} /> <GridFilters availableFilters={availableFilters} appliedFilters={this.state.appliedFilters} onFiltersChange={this.handleFiltersChange} /> </div> </div> <div className="col-md-9"> <Table columns={defaultColumns} keyColumn="number" rows={filteredData} sorting={{ column: 'number' }} /> </div> </div> ); } }
// { fieldName: 'party', dataType: 'string' }, // ];
random_line_split
filters.tsx
import * as React from 'react'; import { AppliedFilter, DataTypes, GridFilters, numberWithCommas, ReactPowerTable, withInternalPaging, withInternalSorting } from '../../src/'; import { defaultColumns, partyList, sampledata } from './shared'; // //if coming in from DTO // const availDTO = [ // { fieldName: 'number', dataType: 'int' }, // { fieldName: 'president', dataType: 'string' }, // { fieldName: 'birth_year', dataType: 'int' }, // { fieldName: 'death_year', dataType: 'int', canBeNull: true }, // { fieldName: 'took_office', dataType: 'date' }, // { fieldName: 'left_office', dataType: 'date', canBeNull: true }, // { fieldName: 'party', dataType: 'string' }, // ]; // const availableFiltersMap = createKeyedMap(availDTO.map(m => new DataTypes[m.dataType](m)), m=>m.fieldName); //availableFilters.party = new DataTypes.list(availableFilters.party, partyList); const partyListOptions = partyList.map(m => ({ label: m.label, value: m.label })); //if building in JS const availableFilters = [ new DataTypes.int('number'), new DataTypes.string('president'), new DataTypes.int('birth_year'), new DataTypes.decimal({ fieldName: 'death_year', canBeNull: true }), new DataTypes.date({ fieldName: 'took_office' }), new DataTypes.date({ fieldName: 'left_office', canBeNull: true }), new DataTypes.list('party', partyListOptions), new DataTypes.boolean({ fieldName: 'assasinated', displayName: 'was assasinated' }), new DataTypes.timespan({ fieldName: 'timeBorn', displayName: 'time born' }), ]; //const columns = [...defaultColumns, { field: m => m.timeBorn, width: 80, formatter: formatTimeValue }]; const assasinatedPresidents = [16, 20, 25, 35]; function padStart(str: string, targetLength: number, padString: string) {
onst data = sampledata.map(m => ({ ...m, assasinated: assasinatedPresidents.indexOf(m.number) > -1, timeBorn: padStart(Math.floor((Math.random() * 24)).toString(), 2, '0') + ':00' })); //const availableFiltersMap = createKeyedMap(availableFilters, m => m.fieldName); //availableFiltersMap.number.operations.gt.displayName = 'greater than TEST'; availableFilters.find(m => m.fieldName === 'death_year').operations['null'].displayName = 'still alive'; interface FiltersExampleState { appliedFilters: Array<AppliedFilter<any>>; } const Table = withInternalSorting(withInternalPaging(ReactPowerTable)); export class FiltersExample extends React.Component<never, FiltersExampleState> { constructor(props: never) { super(props); this.state = { appliedFilters: [] }; this.handleFiltersChange = this.handleFiltersChange.bind(this); } handleFiltersChange(newFilters: Array<AppliedFilter<any>>) { console.log('onFiltersChange', newFilters); this.setState({ appliedFilters: newFilters }); } render() { let filteredData = data; this.state.appliedFilters.forEach(m => { filteredData = m.filter.applyFilter(filteredData, m.operation, m.value); }); return ( <div className="row"> <div className="col-md-3"> <div className="grid-filters"> <div className="small"> {numberWithCommas(filteredData.length) + ' Presidents'} &nbsp; </div> <div style={{ marginTop: 10 }} /> <GridFilters availableFilters={availableFilters} appliedFilters={this.state.appliedFilters} onFiltersChange={this.handleFiltersChange} /> </div> </div> <div className="col-md-9"> <Table columns={defaultColumns} keyColumn="number" rows={filteredData} sorting={{ column: 'number' }} /> </div> </div> ); } }
// tslint:disable-next-line:no-bitwise targetLength = targetLength >> 0; //truncate if number, or convert non-number to 0; padString = String(typeof padString !== 'undefined' ? padString : ' '); if (str.length >= targetLength) { return String(str); } else { targetLength = targetLength - str.length; if (targetLength > padString.length) { padString += padString.repeat(targetLength / padString.length); //append to original to ensure we are longer than needed } return padString.slice(0, targetLength) + str; } } c
identifier_body
dscNodeReportListResult.js
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; /** * The response model for the list dsc nodes operation. */ class DscNodeReportListResult extends Array { /** * Create a DscNodeReportListResult. * @member {string} [nextLink] Gets or sets the next link. */
() { super(); } /** * Defines the metadata of DscNodeReportListResult * * @returns {object} metadata of DscNodeReportListResult * */ mapper() { return { required: false, serializedName: 'DscNodeReportListResult', type: { name: 'Composite', className: 'DscNodeReportListResult', modelProperties: { value: { required: false, serializedName: '', type: { name: 'Sequence', element: { required: false, serializedName: 'DscNodeReportElementType', type: { name: 'Composite', className: 'DscNodeReport' } } } }, nextLink: { required: false, serializedName: 'nextLink', type: { name: 'String' } } } } }; } } module.exports = DscNodeReportListResult;
constructor
identifier_name
dscNodeReportListResult.js
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; /** * The response model for the list dsc nodes operation. */ class DscNodeReportListResult extends Array { /** * Create a DscNodeReportListResult. * @member {string} [nextLink] Gets or sets the next link. */ constructor()
/** * Defines the metadata of DscNodeReportListResult * * @returns {object} metadata of DscNodeReportListResult * */ mapper() { return { required: false, serializedName: 'DscNodeReportListResult', type: { name: 'Composite', className: 'DscNodeReportListResult', modelProperties: { value: { required: false, serializedName: '', type: { name: 'Sequence', element: { required: false, serializedName: 'DscNodeReportElementType', type: { name: 'Composite', className: 'DscNodeReport' } } } }, nextLink: { required: false, serializedName: 'nextLink', type: { name: 'String' } } } } }; } } module.exports = DscNodeReportListResult;
{ super(); }
identifier_body
dscNodeReportListResult.js
* Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; /** * The response model for the list dsc nodes operation. */ class DscNodeReportListResult extends Array { /** * Create a DscNodeReportListResult. * @member {string} [nextLink] Gets or sets the next link. */ constructor() { super(); } /** * Defines the metadata of DscNodeReportListResult * * @returns {object} metadata of DscNodeReportListResult * */ mapper() { return { required: false, serializedName: 'DscNodeReportListResult', type: { name: 'Composite', className: 'DscNodeReportListResult', modelProperties: { value: { required: false, serializedName: '', type: { name: 'Sequence', element: { required: false, serializedName: 'DscNodeReportElementType', type: { name: 'Composite', className: 'DscNodeReport' } } } }, nextLink: { required: false, serializedName: 'nextLink', type: { name: 'String' } } } } }; } } module.exports = DscNodeReportListResult;
/*
random_line_split
cors_cache.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/. */ //! An implementation of the [CORS preflight cache](https://fetch.spec.whatwg.org/#cors-preflight-cache) //! For now this library is XHR-specific. //! For stuff involving `<img>`, `<iframe>`, `<form>`, etc please check what //! the request mode should be and compare with the fetch spec //! This library will eventually become the core of the Fetch crate //! with CORSRequest being expanded into FetchRequest (etc) use hyper::method::Method; use net_traits::request::{CredentialsMode, Origin, Request}; use servo_url::ServoUrl; use std::ascii::AsciiExt; use time::{self, Timespec}; /// Union type for CORS cache entries /// /// Each entry might pertain to a header or method #[derive(Clone, Debug)] pub enum HeaderOrMethod { HeaderData(String), MethodData(Method) } impl HeaderOrMethod { fn match_header(&self, header_name: &str) -> bool { match *self { HeaderOrMethod::HeaderData(ref s) => (&**s).eq_ignore_ascii_case(header_name), _ => false } } fn match_method(&self, method: &Method) -> bool { match *self { HeaderOrMethod::MethodData(ref m) => m == method, _ => false } } } /// An entry in the CORS cache #[derive(Clone, Debug)] pub struct CorsCacheEntry { pub origin: Origin, pub url: ServoUrl, pub max_age: u32, pub credentials: bool, pub header_or_method: HeaderOrMethod, created: Timespec } impl CorsCacheEntry { fn new(origin: Origin, url: ServoUrl, max_age: u32, credentials: bool, header_or_method: HeaderOrMethod) -> CorsCacheEntry { CorsCacheEntry { origin: origin, url: url, max_age: max_age, credentials: credentials, header_or_method: header_or_method, created: time::now().to_timespec() } } } fn match_headers(cors_cache: &CorsCacheEntry, cors_req: &Request) -> bool { cors_cache.origin == cors_req.origin && cors_cache.url == cors_req.current_url() && (cors_cache.credentials || cors_req.credentials_mode != CredentialsMode::Include) } /// A simple, vector-based CORS Cache #[derive(Clone)] pub struct CorsCache(Vec<CorsCacheEntry>); impl CorsCache { pub fn new() -> CorsCache { CorsCache(vec![]) } fn find_entry_by_header<'a>(&'a mut self, request: &Request, header_name: &str) -> Option<&'a mut CorsCacheEntry> { self.cleanup(); self.0.iter_mut().find(|e| match_headers(e, request) && e.header_or_method.match_header(header_name)) } fn find_entry_by_method<'a>(&'a mut self, request: &Request, method: Method) -> Option<&'a mut CorsCacheEntry> { // we can take the method from CorSRequest itself self.cleanup(); self.0.iter_mut().find(|e| match_headers(e, request) && e.header_or_method.match_method(&method)) } /// [Clear the cache](https://fetch.spec.whatwg.org/#concept-cache-clear) pub fn clear(&mut self, request: &Request) { let CorsCache(buf) = self.clone(); let new_buf: Vec<CorsCacheEntry> = buf.into_iter().filter(|e| e.origin == request.origin && request.current_url() == e.url).collect(); *self = CorsCache(new_buf); } /// Remove old entries pub fn cleanup(&mut self) { let CorsCache(buf) = self.clone(); let now = time::now().to_timespec(); let new_buf: Vec<CorsCacheEntry> = buf.into_iter() .filter(|e| now.sec < e.created.sec + e.max_age as i64) .collect(); *self = CorsCache(new_buf); } /// Returns true if an entry with a /// [matching header](https://fetch.spec.whatwg.org/#concept-cache-match-header) is found pub fn match_header(&mut self, request: &Request, header_name: &str) -> bool { self.find_entry_by_header(&request, header_name).is_some() } /// Updates max age if an entry for a /// [matching header](https://fetch.spec.whatwg.org/#concept-cache-match-header) is found. /// /// If not, it will insert an equivalent entry pub fn match_header_and_update(&mut self, request: &Request, header_name: &str, new_max_age: u32) -> bool { match self.find_entry_by_header(&request, header_name).map(|e| e.max_age = new_max_age) { Some(_) => true, None => { self.insert(CorsCacheEntry::new(request.origin.clone(), request.current_url(), new_max_age, request.credentials_mode == CredentialsMode::Include, HeaderOrMethod::HeaderData(header_name.to_owned()))); false } } } /// Returns true if an entry with a /// [matching method](https://fetch.spec.whatwg.org/#concept-cache-match-method) is found pub fn
(&mut self, request: &Request, method: Method) -> bool { self.find_entry_by_method(&request, method).is_some() } /// Updates max age if an entry for /// [a matching method](https://fetch.spec.whatwg.org/#concept-cache-match-method) is found. /// /// If not, it will insert an equivalent entry pub fn match_method_and_update(&mut self, request: &Request, method: Method, new_max_age: u32) -> bool { match self.find_entry_by_method(&request, method.clone()).map(|e| e.max_age = new_max_age) { Some(_) => true, None => { self.insert(CorsCacheEntry::new(request.origin.clone(), request.current_url(), new_max_age, request.credentials_mode == CredentialsMode::Include, HeaderOrMethod::MethodData(method))); false } } } /// Insert an entry pub fn insert(&mut self, entry: CorsCacheEntry) { self.cleanup(); self.0.push(entry); } }
match_method
identifier_name
cors_cache.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/. */ //! An implementation of the [CORS preflight cache](https://fetch.spec.whatwg.org/#cors-preflight-cache) //! For now this library is XHR-specific. //! For stuff involving `<img>`, `<iframe>`, `<form>`, etc please check what //! the request mode should be and compare with the fetch spec //! This library will eventually become the core of the Fetch crate //! with CORSRequest being expanded into FetchRequest (etc) use hyper::method::Method; use net_traits::request::{CredentialsMode, Origin, Request}; use servo_url::ServoUrl; use std::ascii::AsciiExt; use time::{self, Timespec}; /// Union type for CORS cache entries /// /// Each entry might pertain to a header or method #[derive(Clone, Debug)] pub enum HeaderOrMethod { HeaderData(String), MethodData(Method) } impl HeaderOrMethod { fn match_header(&self, header_name: &str) -> bool { match *self { HeaderOrMethod::HeaderData(ref s) => (&**s).eq_ignore_ascii_case(header_name), _ => false } } fn match_method(&self, method: &Method) -> bool { match *self { HeaderOrMethod::MethodData(ref m) => m == method, _ => false } } } /// An entry in the CORS cache #[derive(Clone, Debug)] pub struct CorsCacheEntry { pub origin: Origin, pub url: ServoUrl,
impl CorsCacheEntry { fn new(origin: Origin, url: ServoUrl, max_age: u32, credentials: bool, header_or_method: HeaderOrMethod) -> CorsCacheEntry { CorsCacheEntry { origin: origin, url: url, max_age: max_age, credentials: credentials, header_or_method: header_or_method, created: time::now().to_timespec() } } } fn match_headers(cors_cache: &CorsCacheEntry, cors_req: &Request) -> bool { cors_cache.origin == cors_req.origin && cors_cache.url == cors_req.current_url() && (cors_cache.credentials || cors_req.credentials_mode != CredentialsMode::Include) } /// A simple, vector-based CORS Cache #[derive(Clone)] pub struct CorsCache(Vec<CorsCacheEntry>); impl CorsCache { pub fn new() -> CorsCache { CorsCache(vec![]) } fn find_entry_by_header<'a>(&'a mut self, request: &Request, header_name: &str) -> Option<&'a mut CorsCacheEntry> { self.cleanup(); self.0.iter_mut().find(|e| match_headers(e, request) && e.header_or_method.match_header(header_name)) } fn find_entry_by_method<'a>(&'a mut self, request: &Request, method: Method) -> Option<&'a mut CorsCacheEntry> { // we can take the method from CorSRequest itself self.cleanup(); self.0.iter_mut().find(|e| match_headers(e, request) && e.header_or_method.match_method(&method)) } /// [Clear the cache](https://fetch.spec.whatwg.org/#concept-cache-clear) pub fn clear(&mut self, request: &Request) { let CorsCache(buf) = self.clone(); let new_buf: Vec<CorsCacheEntry> = buf.into_iter().filter(|e| e.origin == request.origin && request.current_url() == e.url).collect(); *self = CorsCache(new_buf); } /// Remove old entries pub fn cleanup(&mut self) { let CorsCache(buf) = self.clone(); let now = time::now().to_timespec(); let new_buf: Vec<CorsCacheEntry> = buf.into_iter() .filter(|e| now.sec < e.created.sec + e.max_age as i64) .collect(); *self = CorsCache(new_buf); } /// Returns true if an entry with a /// [matching header](https://fetch.spec.whatwg.org/#concept-cache-match-header) is found pub fn match_header(&mut self, request: &Request, header_name: &str) -> bool { self.find_entry_by_header(&request, header_name).is_some() } /// Updates max age if an entry for a /// [matching header](https://fetch.spec.whatwg.org/#concept-cache-match-header) is found. /// /// If not, it will insert an equivalent entry pub fn match_header_and_update(&mut self, request: &Request, header_name: &str, new_max_age: u32) -> bool { match self.find_entry_by_header(&request, header_name).map(|e| e.max_age = new_max_age) { Some(_) => true, None => { self.insert(CorsCacheEntry::new(request.origin.clone(), request.current_url(), new_max_age, request.credentials_mode == CredentialsMode::Include, HeaderOrMethod::HeaderData(header_name.to_owned()))); false } } } /// Returns true if an entry with a /// [matching method](https://fetch.spec.whatwg.org/#concept-cache-match-method) is found pub fn match_method(&mut self, request: &Request, method: Method) -> bool { self.find_entry_by_method(&request, method).is_some() } /// Updates max age if an entry for /// [a matching method](https://fetch.spec.whatwg.org/#concept-cache-match-method) is found. /// /// If not, it will insert an equivalent entry pub fn match_method_and_update(&mut self, request: &Request, method: Method, new_max_age: u32) -> bool { match self.find_entry_by_method(&request, method.clone()).map(|e| e.max_age = new_max_age) { Some(_) => true, None => { self.insert(CorsCacheEntry::new(request.origin.clone(), request.current_url(), new_max_age, request.credentials_mode == CredentialsMode::Include, HeaderOrMethod::MethodData(method))); false } } } /// Insert an entry pub fn insert(&mut self, entry: CorsCacheEntry) { self.cleanup(); self.0.push(entry); } }
pub max_age: u32, pub credentials: bool, pub header_or_method: HeaderOrMethod, created: Timespec }
random_line_split
cors_cache.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/. */ //! An implementation of the [CORS preflight cache](https://fetch.spec.whatwg.org/#cors-preflight-cache) //! For now this library is XHR-specific. //! For stuff involving `<img>`, `<iframe>`, `<form>`, etc please check what //! the request mode should be and compare with the fetch spec //! This library will eventually become the core of the Fetch crate //! with CORSRequest being expanded into FetchRequest (etc) use hyper::method::Method; use net_traits::request::{CredentialsMode, Origin, Request}; use servo_url::ServoUrl; use std::ascii::AsciiExt; use time::{self, Timespec}; /// Union type for CORS cache entries /// /// Each entry might pertain to a header or method #[derive(Clone, Debug)] pub enum HeaderOrMethod { HeaderData(String), MethodData(Method) } impl HeaderOrMethod { fn match_header(&self, header_name: &str) -> bool { match *self { HeaderOrMethod::HeaderData(ref s) => (&**s).eq_ignore_ascii_case(header_name), _ => false } } fn match_method(&self, method: &Method) -> bool { match *self { HeaderOrMethod::MethodData(ref m) => m == method, _ => false } } } /// An entry in the CORS cache #[derive(Clone, Debug)] pub struct CorsCacheEntry { pub origin: Origin, pub url: ServoUrl, pub max_age: u32, pub credentials: bool, pub header_or_method: HeaderOrMethod, created: Timespec } impl CorsCacheEntry { fn new(origin: Origin, url: ServoUrl, max_age: u32, credentials: bool, header_or_method: HeaderOrMethod) -> CorsCacheEntry { CorsCacheEntry { origin: origin, url: url, max_age: max_age, credentials: credentials, header_or_method: header_or_method, created: time::now().to_timespec() } } } fn match_headers(cors_cache: &CorsCacheEntry, cors_req: &Request) -> bool
/// A simple, vector-based CORS Cache #[derive(Clone)] pub struct CorsCache(Vec<CorsCacheEntry>); impl CorsCache { pub fn new() -> CorsCache { CorsCache(vec![]) } fn find_entry_by_header<'a>(&'a mut self, request: &Request, header_name: &str) -> Option<&'a mut CorsCacheEntry> { self.cleanup(); self.0.iter_mut().find(|e| match_headers(e, request) && e.header_or_method.match_header(header_name)) } fn find_entry_by_method<'a>(&'a mut self, request: &Request, method: Method) -> Option<&'a mut CorsCacheEntry> { // we can take the method from CorSRequest itself self.cleanup(); self.0.iter_mut().find(|e| match_headers(e, request) && e.header_or_method.match_method(&method)) } /// [Clear the cache](https://fetch.spec.whatwg.org/#concept-cache-clear) pub fn clear(&mut self, request: &Request) { let CorsCache(buf) = self.clone(); let new_buf: Vec<CorsCacheEntry> = buf.into_iter().filter(|e| e.origin == request.origin && request.current_url() == e.url).collect(); *self = CorsCache(new_buf); } /// Remove old entries pub fn cleanup(&mut self) { let CorsCache(buf) = self.clone(); let now = time::now().to_timespec(); let new_buf: Vec<CorsCacheEntry> = buf.into_iter() .filter(|e| now.sec < e.created.sec + e.max_age as i64) .collect(); *self = CorsCache(new_buf); } /// Returns true if an entry with a /// [matching header](https://fetch.spec.whatwg.org/#concept-cache-match-header) is found pub fn match_header(&mut self, request: &Request, header_name: &str) -> bool { self.find_entry_by_header(&request, header_name).is_some() } /// Updates max age if an entry for a /// [matching header](https://fetch.spec.whatwg.org/#concept-cache-match-header) is found. /// /// If not, it will insert an equivalent entry pub fn match_header_and_update(&mut self, request: &Request, header_name: &str, new_max_age: u32) -> bool { match self.find_entry_by_header(&request, header_name).map(|e| e.max_age = new_max_age) { Some(_) => true, None => { self.insert(CorsCacheEntry::new(request.origin.clone(), request.current_url(), new_max_age, request.credentials_mode == CredentialsMode::Include, HeaderOrMethod::HeaderData(header_name.to_owned()))); false } } } /// Returns true if an entry with a /// [matching method](https://fetch.spec.whatwg.org/#concept-cache-match-method) is found pub fn match_method(&mut self, request: &Request, method: Method) -> bool { self.find_entry_by_method(&request, method).is_some() } /// Updates max age if an entry for /// [a matching method](https://fetch.spec.whatwg.org/#concept-cache-match-method) is found. /// /// If not, it will insert an equivalent entry pub fn match_method_and_update(&mut self, request: &Request, method: Method, new_max_age: u32) -> bool { match self.find_entry_by_method(&request, method.clone()).map(|e| e.max_age = new_max_age) { Some(_) => true, None => { self.insert(CorsCacheEntry::new(request.origin.clone(), request.current_url(), new_max_age, request.credentials_mode == CredentialsMode::Include, HeaderOrMethod::MethodData(method))); false } } } /// Insert an entry pub fn insert(&mut self, entry: CorsCacheEntry) { self.cleanup(); self.0.push(entry); } }
{ cors_cache.origin == cors_req.origin && cors_cache.url == cors_req.current_url() && (cors_cache.credentials || cors_req.credentials_mode != CredentialsMode::Include) }
identifier_body
index.js
import React, { PropTypes as T } from 'react'; import ReactModal2 from 'react-modal2'; export default class Modal extends React.Component { static propTypes = { children: T.node, onClose: T.func.isRequired, closeOnEsc: T.bool, closeOnBackdropClick: T.bool, }; static defaultProps = { closeOnEsc: true, closeOnBackdropClick: true, onClose: () => { }, }; constructor(props) { super(props); this.handleBackdropClick = this.handleBackdropClick.bind(this); } handleBackdropClick() { const { onClose, closeOnBackdropClick } = this.props; if (closeOnBackdropClick)
} render() { const { onClose, closeOnEsc, closeOnBackdropClick, children, } = this.props; return ( <ReactModal2 onClose={onClose} closeOnEsc={closeOnEsc} closeOnBackdropClick={closeOnBackdropClick} backdropClassName="Modal" modalClassName="Modal-content" > <div className="Modal-close" onClick={this.handleBackdropClick}> {children} </div> </ReactModal2> ); } }
{ onClose(); }
conditional_block
index.js
import React, { PropTypes as T } from 'react'; import ReactModal2 from 'react-modal2'; export default class Modal extends React.Component { static propTypes = { children: T.node, onClose: T.func.isRequired, closeOnEsc: T.bool, closeOnBackdropClick: T.bool, }; static defaultProps = { closeOnEsc: true, closeOnBackdropClick: true, onClose: () => { }, }; constructor(props) { super(props); this.handleBackdropClick = this.handleBackdropClick.bind(this); }
() { const { onClose, closeOnBackdropClick } = this.props; if (closeOnBackdropClick) { onClose(); } } render() { const { onClose, closeOnEsc, closeOnBackdropClick, children, } = this.props; return ( <ReactModal2 onClose={onClose} closeOnEsc={closeOnEsc} closeOnBackdropClick={closeOnBackdropClick} backdropClassName="Modal" modalClassName="Modal-content" > <div className="Modal-close" onClick={this.handleBackdropClick}> {children} </div> </ReactModal2> ); } }
handleBackdropClick
identifier_name
index.js
import React, { PropTypes as T } from 'react'; import ReactModal2 from 'react-modal2'; export default class Modal extends React.Component { static propTypes = { children: T.node, onClose: T.func.isRequired, closeOnEsc: T.bool, closeOnBackdropClick: T.bool, }; static defaultProps = { closeOnEsc: true, closeOnBackdropClick: true, onClose: () => { }, }; constructor(props) { super(props); this.handleBackdropClick = this.handleBackdropClick.bind(this); } handleBackdropClick()
render() { const { onClose, closeOnEsc, closeOnBackdropClick, children, } = this.props; return ( <ReactModal2 onClose={onClose} closeOnEsc={closeOnEsc} closeOnBackdropClick={closeOnBackdropClick} backdropClassName="Modal" modalClassName="Modal-content" > <div className="Modal-close" onClick={this.handleBackdropClick}> {children} </div> </ReactModal2> ); } }
{ const { onClose, closeOnBackdropClick } = this.props; if (closeOnBackdropClick) { onClose(); } }
identifier_body
index.js
import React, { PropTypes as T } from 'react'; import ReactModal2 from 'react-modal2'; export default class Modal extends React.Component { static propTypes = { children: T.node, onClose: T.func.isRequired, closeOnEsc: T.bool, closeOnBackdropClick: T.bool, }; static defaultProps = { closeOnEsc: true, closeOnBackdropClick: true, onClose: () => { }, }; constructor(props) { super(props); this.handleBackdropClick = this.handleBackdropClick.bind(this); } handleBackdropClick() { const { onClose, closeOnBackdropClick } = this.props; if (closeOnBackdropClick) { onClose(); } } render() { const { onClose, closeOnEsc,
<ReactModal2 onClose={onClose} closeOnEsc={closeOnEsc} closeOnBackdropClick={closeOnBackdropClick} backdropClassName="Modal" modalClassName="Modal-content" > <div className="Modal-close" onClick={this.handleBackdropClick}> {children} </div> </ReactModal2> ); } }
closeOnBackdropClick, children, } = this.props; return (
random_line_split
kd_tree_edges_mk2.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### import bpy from bpy.props import IntProperty, FloatProperty import mathutils from sverchok.node_tree import SverchCustomTreeNode from sverchok.data_structure import updateNode # documentation/blender_python_api_2_70_release/mathutils.kdtree.html class SvKDTreeEdgesNodeMK2(bpy.types.Node, SverchCustomTreeNode): bl_idname = 'SvKDTreeEdgesNodeMK2' bl_label = 'KDT Closest Edges MK2' bl_icon = 'OUTLINER_OB_EMPTY' mindist = FloatProperty( name='mindist', description='Minimum dist', min=0.0, default=0.1, update=updateNode) maxdist = FloatProperty( name='maxdist', description='Maximum dist', min=0.0, default=2.0, update=updateNode) maxNum = IntProperty( name='maxNum', description='max edge count', default=4, min=1, update=updateNode) skip = IntProperty( name='skip', description='skip first n', default=0, min=0, update=updateNode) def sv_init(self, context): self.inputs.new('VerticesSocket', 'Verts') self.inputs.new('StringsSocket', 'mindist').prop_name = 'mindist' self.inputs.new('StringsSocket', 'maxdist').prop_name = 'maxdist' self.inputs.new('StringsSocket', 'maxNum').prop_name = 'maxNum' self.inputs.new('StringsSocket', 'skip').prop_name = 'skip' self.outputs.new('StringsSocket', 'Edges') def process(self): inputs = self.inputs outputs = self.outputs try: verts = inputs['Verts'].sv_get()[0] linked = outputs['Edges'].is_linked except (IndexError, KeyError) as e: return optional_sockets = [ ['mindist', self.mindist, float], ['maxdist', self.maxdist, float], ['maxNum', self.maxNum, int], ['skip', self.skip, int]] socket_inputs = [] for s, s_default_value, dtype in optional_sockets: if s in inputs and inputs[s].is_linked: sock_input = dtype(inputs[s].sv_get()[0][0]) else: sock_input = s_default_value socket_inputs.append(sock_input) self.run_kdtree(verts, socket_inputs) def run_kdtree(self, verts, socket_inputs): mindist, maxdist, maxNum, skip = socket_inputs # make kdtree # documentation/blender_python_api_2_78_release/mathutils.kdtree.html size = len(verts) kd = mathutils.kdtree.KDTree(size) for i, xyz in enumerate(verts): kd.insert(xyz, i) kd.balance() # set minimum values maxNum = max(maxNum, 1) skip = max(skip, 0) # makes edges e = set() for i, vtx in enumerate(verts): num_edges = 0 # this always returns closest first followed by next closest, etc. # co index dist for edge_idx, (_, index, dist) in enumerate(kd.find_range(vtx, abs(maxdist))): if skip > 0: if edge_idx < skip: continue if (dist <= abs(mindist)) or (i == index): continue edge = tuple(sorted([i, index])) if not edge in e: e.add(edge) num_edges += 1 if num_edges == maxNum: break self.outputs['Edges'].sv_set([list(e)]) def
(): bpy.utils.register_class(SvKDTreeEdgesNodeMK2) def unregister(): bpy.utils.unregister_class(SvKDTreeEdgesNodeMK2)
register
identifier_name
kd_tree_edges_mk2.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### import bpy from bpy.props import IntProperty, FloatProperty import mathutils from sverchok.node_tree import SverchCustomTreeNode from sverchok.data_structure import updateNode # documentation/blender_python_api_2_70_release/mathutils.kdtree.html class SvKDTreeEdgesNodeMK2(bpy.types.Node, SverchCustomTreeNode): bl_idname = 'SvKDTreeEdgesNodeMK2' bl_label = 'KDT Closest Edges MK2' bl_icon = 'OUTLINER_OB_EMPTY' mindist = FloatProperty( name='mindist', description='Minimum dist', min=0.0, default=0.1, update=updateNode) maxdist = FloatProperty(
name='maxNum', description='max edge count', default=4, min=1, update=updateNode) skip = IntProperty( name='skip', description='skip first n', default=0, min=0, update=updateNode) def sv_init(self, context): self.inputs.new('VerticesSocket', 'Verts') self.inputs.new('StringsSocket', 'mindist').prop_name = 'mindist' self.inputs.new('StringsSocket', 'maxdist').prop_name = 'maxdist' self.inputs.new('StringsSocket', 'maxNum').prop_name = 'maxNum' self.inputs.new('StringsSocket', 'skip').prop_name = 'skip' self.outputs.new('StringsSocket', 'Edges') def process(self): inputs = self.inputs outputs = self.outputs try: verts = inputs['Verts'].sv_get()[0] linked = outputs['Edges'].is_linked except (IndexError, KeyError) as e: return optional_sockets = [ ['mindist', self.mindist, float], ['maxdist', self.maxdist, float], ['maxNum', self.maxNum, int], ['skip', self.skip, int]] socket_inputs = [] for s, s_default_value, dtype in optional_sockets: if s in inputs and inputs[s].is_linked: sock_input = dtype(inputs[s].sv_get()[0][0]) else: sock_input = s_default_value socket_inputs.append(sock_input) self.run_kdtree(verts, socket_inputs) def run_kdtree(self, verts, socket_inputs): mindist, maxdist, maxNum, skip = socket_inputs # make kdtree # documentation/blender_python_api_2_78_release/mathutils.kdtree.html size = len(verts) kd = mathutils.kdtree.KDTree(size) for i, xyz in enumerate(verts): kd.insert(xyz, i) kd.balance() # set minimum values maxNum = max(maxNum, 1) skip = max(skip, 0) # makes edges e = set() for i, vtx in enumerate(verts): num_edges = 0 # this always returns closest first followed by next closest, etc. # co index dist for edge_idx, (_, index, dist) in enumerate(kd.find_range(vtx, abs(maxdist))): if skip > 0: if edge_idx < skip: continue if (dist <= abs(mindist)) or (i == index): continue edge = tuple(sorted([i, index])) if not edge in e: e.add(edge) num_edges += 1 if num_edges == maxNum: break self.outputs['Edges'].sv_set([list(e)]) def register(): bpy.utils.register_class(SvKDTreeEdgesNodeMK2) def unregister(): bpy.utils.unregister_class(SvKDTreeEdgesNodeMK2)
name='maxdist', description='Maximum dist', min=0.0, default=2.0, update=updateNode) maxNum = IntProperty(
random_line_split
kd_tree_edges_mk2.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### import bpy from bpy.props import IntProperty, FloatProperty import mathutils from sverchok.node_tree import SverchCustomTreeNode from sverchok.data_structure import updateNode # documentation/blender_python_api_2_70_release/mathutils.kdtree.html class SvKDTreeEdgesNodeMK2(bpy.types.Node, SverchCustomTreeNode): bl_idname = 'SvKDTreeEdgesNodeMK2' bl_label = 'KDT Closest Edges MK2' bl_icon = 'OUTLINER_OB_EMPTY' mindist = FloatProperty( name='mindist', description='Minimum dist', min=0.0, default=0.1, update=updateNode) maxdist = FloatProperty( name='maxdist', description='Maximum dist', min=0.0, default=2.0, update=updateNode) maxNum = IntProperty( name='maxNum', description='max edge count', default=4, min=1, update=updateNode) skip = IntProperty( name='skip', description='skip first n', default=0, min=0, update=updateNode) def sv_init(self, context): self.inputs.new('VerticesSocket', 'Verts') self.inputs.new('StringsSocket', 'mindist').prop_name = 'mindist' self.inputs.new('StringsSocket', 'maxdist').prop_name = 'maxdist' self.inputs.new('StringsSocket', 'maxNum').prop_name = 'maxNum' self.inputs.new('StringsSocket', 'skip').prop_name = 'skip' self.outputs.new('StringsSocket', 'Edges') def process(self): inputs = self.inputs outputs = self.outputs try: verts = inputs['Verts'].sv_get()[0] linked = outputs['Edges'].is_linked except (IndexError, KeyError) as e: return optional_sockets = [ ['mindist', self.mindist, float], ['maxdist', self.maxdist, float], ['maxNum', self.maxNum, int], ['skip', self.skip, int]] socket_inputs = [] for s, s_default_value, dtype in optional_sockets: if s in inputs and inputs[s].is_linked: sock_input = dtype(inputs[s].sv_get()[0][0]) else: sock_input = s_default_value socket_inputs.append(sock_input) self.run_kdtree(verts, socket_inputs) def run_kdtree(self, verts, socket_inputs): mindist, maxdist, maxNum, skip = socket_inputs # make kdtree # documentation/blender_python_api_2_78_release/mathutils.kdtree.html size = len(verts) kd = mathutils.kdtree.KDTree(size) for i, xyz in enumerate(verts): kd.insert(xyz, i) kd.balance() # set minimum values maxNum = max(maxNum, 1) skip = max(skip, 0) # makes edges e = set() for i, vtx in enumerate(verts): num_edges = 0 # this always returns closest first followed by next closest, etc. # co index dist for edge_idx, (_, index, dist) in enumerate(kd.find_range(vtx, abs(maxdist))): if skip > 0: if edge_idx < skip:
if (dist <= abs(mindist)) or (i == index): continue edge = tuple(sorted([i, index])) if not edge in e: e.add(edge) num_edges += 1 if num_edges == maxNum: break self.outputs['Edges'].sv_set([list(e)]) def register(): bpy.utils.register_class(SvKDTreeEdgesNodeMK2) def unregister(): bpy.utils.unregister_class(SvKDTreeEdgesNodeMK2)
continue
conditional_block
kd_tree_edges_mk2.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### import bpy from bpy.props import IntProperty, FloatProperty import mathutils from sverchok.node_tree import SverchCustomTreeNode from sverchok.data_structure import updateNode # documentation/blender_python_api_2_70_release/mathutils.kdtree.html class SvKDTreeEdgesNodeMK2(bpy.types.Node, SverchCustomTreeNode):
def register(): bpy.utils.register_class(SvKDTreeEdgesNodeMK2) def unregister(): bpy.utils.unregister_class(SvKDTreeEdgesNodeMK2)
bl_idname = 'SvKDTreeEdgesNodeMK2' bl_label = 'KDT Closest Edges MK2' bl_icon = 'OUTLINER_OB_EMPTY' mindist = FloatProperty( name='mindist', description='Minimum dist', min=0.0, default=0.1, update=updateNode) maxdist = FloatProperty( name='maxdist', description='Maximum dist', min=0.0, default=2.0, update=updateNode) maxNum = IntProperty( name='maxNum', description='max edge count', default=4, min=1, update=updateNode) skip = IntProperty( name='skip', description='skip first n', default=0, min=0, update=updateNode) def sv_init(self, context): self.inputs.new('VerticesSocket', 'Verts') self.inputs.new('StringsSocket', 'mindist').prop_name = 'mindist' self.inputs.new('StringsSocket', 'maxdist').prop_name = 'maxdist' self.inputs.new('StringsSocket', 'maxNum').prop_name = 'maxNum' self.inputs.new('StringsSocket', 'skip').prop_name = 'skip' self.outputs.new('StringsSocket', 'Edges') def process(self): inputs = self.inputs outputs = self.outputs try: verts = inputs['Verts'].sv_get()[0] linked = outputs['Edges'].is_linked except (IndexError, KeyError) as e: return optional_sockets = [ ['mindist', self.mindist, float], ['maxdist', self.maxdist, float], ['maxNum', self.maxNum, int], ['skip', self.skip, int]] socket_inputs = [] for s, s_default_value, dtype in optional_sockets: if s in inputs and inputs[s].is_linked: sock_input = dtype(inputs[s].sv_get()[0][0]) else: sock_input = s_default_value socket_inputs.append(sock_input) self.run_kdtree(verts, socket_inputs) def run_kdtree(self, verts, socket_inputs): mindist, maxdist, maxNum, skip = socket_inputs # make kdtree # documentation/blender_python_api_2_78_release/mathutils.kdtree.html size = len(verts) kd = mathutils.kdtree.KDTree(size) for i, xyz in enumerate(verts): kd.insert(xyz, i) kd.balance() # set minimum values maxNum = max(maxNum, 1) skip = max(skip, 0) # makes edges e = set() for i, vtx in enumerate(verts): num_edges = 0 # this always returns closest first followed by next closest, etc. # co index dist for edge_idx, (_, index, dist) in enumerate(kd.find_range(vtx, abs(maxdist))): if skip > 0: if edge_idx < skip: continue if (dist <= abs(mindist)) or (i == index): continue edge = tuple(sorted([i, index])) if not edge in e: e.add(edge) num_edges += 1 if num_edges == maxNum: break self.outputs['Edges'].sv_set([list(e)])
identifier_body
ContactCanvas.py
# -*- coding: utf-8 -*- # Copyright (c) 2008 - 2009 Lukas Hetzenecker <LuHe@gmx.at> from PyQt4.QtCore import * from PyQt4.QtGui import * # Matplotlib try: from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt4 import NavigationToolbar2QT as NavigationToolbar from matplotlib.figure import Figure except ImportError: USE_MATPLOTLIB = False else: USE_MATPLOTLIB= True if USE_MATPLOTLIB: class ContactCanvas(FigureCanvas): def __init__(self, parent=None, width = 10, height = 3, dpi = 100, sharex = None, sharey = None): self.fig = Figure(figsize = (width, height), dpi=dpi, facecolor = '#FFFFFF') self.ax = self.fig.add_subplot(111, sharex = sharex, sharey = sharey) FigureCanvas.__init__(self, self.fig) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) def format_labels(self): labels_x = self.ax.get_xticklabels() labels_y = self.ax.get_yticklabels() for xlabel in labels_x: xlabel.set_fontsize(8) for ylabel in labels_y: ylabel.set_fontsize(8) ylabel.set_color('b') else: class ContactCanvas(QLabel): def
(self, parent=None): super(ContactCanvas, self).__init__(parent) self.setText(self.tr("Matplotlib not found - Please install it."))
__init__
identifier_name
ContactCanvas.py
# -*- coding: utf-8 -*- # Copyright (c) 2008 - 2009 Lukas Hetzenecker <LuHe@gmx.at> from PyQt4.QtCore import * from PyQt4.QtGui import * # Matplotlib try: from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt4 import NavigationToolbar2QT as NavigationToolbar from matplotlib.figure import Figure except ImportError: USE_MATPLOTLIB = False else:
if USE_MATPLOTLIB: class ContactCanvas(FigureCanvas): def __init__(self, parent=None, width = 10, height = 3, dpi = 100, sharex = None, sharey = None): self.fig = Figure(figsize = (width, height), dpi=dpi, facecolor = '#FFFFFF') self.ax = self.fig.add_subplot(111, sharex = sharex, sharey = sharey) FigureCanvas.__init__(self, self.fig) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) def format_labels(self): labels_x = self.ax.get_xticklabels() labels_y = self.ax.get_yticklabels() for xlabel in labels_x: xlabel.set_fontsize(8) for ylabel in labels_y: ylabel.set_fontsize(8) ylabel.set_color('b') else: class ContactCanvas(QLabel): def __init__(self, parent=None): super(ContactCanvas, self).__init__(parent) self.setText(self.tr("Matplotlib not found - Please install it."))
USE_MATPLOTLIB= True
conditional_block
ContactCanvas.py
# -*- coding: utf-8 -*- # Copyright (c) 2008 - 2009 Lukas Hetzenecker <LuHe@gmx.at> from PyQt4.QtCore import * from PyQt4.QtGui import * # Matplotlib try: from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt4 import NavigationToolbar2QT as NavigationToolbar from matplotlib.figure import Figure except ImportError: USE_MATPLOTLIB = False else: USE_MATPLOTLIB= True if USE_MATPLOTLIB: class ContactCanvas(FigureCanvas): def __init__(self, parent=None, width = 10, height = 3, dpi = 100, sharex = None, sharey = None): self.fig = Figure(figsize = (width, height), dpi=dpi, facecolor = '#FFFFFF') self.ax = self.fig.add_subplot(111, sharex = sharex, sharey = sharey) FigureCanvas.__init__(self, self.fig) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) def format_labels(self): labels_x = self.ax.get_xticklabels() labels_y = self.ax.get_yticklabels() for xlabel in labels_x: xlabel.set_fontsize(8) for ylabel in labels_y: ylabel.set_fontsize(8) ylabel.set_color('b') else: class ContactCanvas(QLabel):
def __init__(self, parent=None): super(ContactCanvas, self).__init__(parent) self.setText(self.tr("Matplotlib not found - Please install it."))
identifier_body
ContactCanvas.py
# -*- coding: utf-8 -*- # Copyright (c) 2008 - 2009 Lukas Hetzenecker <LuHe@gmx.at> from PyQt4.QtCore import * from PyQt4.QtGui import * # Matplotlib try: from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt4 import NavigationToolbar2QT as NavigationToolbar from matplotlib.figure import Figure except ImportError: USE_MATPLOTLIB = False else: USE_MATPLOTLIB= True if USE_MATPLOTLIB: class ContactCanvas(FigureCanvas): def __init__(self, parent=None, width = 10, height = 3, dpi = 100, sharex = None, sharey = None): self.fig = Figure(figsize = (width, height), dpi=dpi, facecolor = '#FFFFFF') self.ax = self.fig.add_subplot(111, sharex = sharex, sharey = sharey) FigureCanvas.__init__(self, self.fig) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) def format_labels(self): labels_x = self.ax.get_xticklabels() labels_y = self.ax.get_yticklabels() for xlabel in labels_x: xlabel.set_fontsize(8) for ylabel in labels_y: ylabel.set_fontsize(8) ylabel.set_color('b') else:
class ContactCanvas(QLabel): def __init__(self, parent=None): super(ContactCanvas, self).__init__(parent) self.setText(self.tr("Matplotlib not found - Please install it."))
random_line_split
cross-global-eval-is-indirect.js
// |reftest| skip-if(!xulRuntime.shell) -- needs newGlobal() /* * Any copyright is dedicated to the Public Domain. * http://creativecommons.org/licenses/publicdomain/ */ //----------------------------------------------------------------------------- var BUGNUMBER = 608473; var summary = '|var eval = otherWindow.eval; eval(...)| should behave like indirectly ' + 'calling that eval from a script in that other window'; print(BUGNUMBER + ": " + summary); /**************
**************/ var originalEval = eval; var res; function f() { return [this, eval("this")]; } var otherGlobalSameCompartment = newGlobal("same-compartment"); eval = otherGlobalSameCompartment.eval; res = new f(); assertEq(res[0] !== res[1], true); assertEq(res[0] !== this, true); assertEq(res[0] instanceof f, true); assertEq(res[1], otherGlobalSameCompartment); res = f(); assertEq(res[0] !== res[1], true); assertEq(res[0], this); assertEq(res[1], otherGlobalSameCompartment); var otherGlobalDifferentCompartment = newGlobal(); eval = otherGlobalDifferentCompartment.eval; res = new f(); assertEq(res[0] !== res[1], true); assertEq(res[0] !== this, true); assertEq(res[0] instanceof f, true); assertEq(res[1], otherGlobalDifferentCompartment); res = f(); assertEq(res[0] !== res[1], true); assertEq(res[0], this); assertEq(res[1], otherGlobalDifferentCompartment); /******************************************************************************/ if (typeof reportCompare === "function") reportCompare(true, true); print("All tests passed!");
* BEGIN TEST *
random_line_split
cross-global-eval-is-indirect.js
// |reftest| skip-if(!xulRuntime.shell) -- needs newGlobal() /* * Any copyright is dedicated to the Public Domain. * http://creativecommons.org/licenses/publicdomain/ */ //----------------------------------------------------------------------------- var BUGNUMBER = 608473; var summary = '|var eval = otherWindow.eval; eval(...)| should behave like indirectly ' + 'calling that eval from a script in that other window'; print(BUGNUMBER + ": " + summary); /************** * BEGIN TEST * **************/ var originalEval = eval; var res; function
() { return [this, eval("this")]; } var otherGlobalSameCompartment = newGlobal("same-compartment"); eval = otherGlobalSameCompartment.eval; res = new f(); assertEq(res[0] !== res[1], true); assertEq(res[0] !== this, true); assertEq(res[0] instanceof f, true); assertEq(res[1], otherGlobalSameCompartment); res = f(); assertEq(res[0] !== res[1], true); assertEq(res[0], this); assertEq(res[1], otherGlobalSameCompartment); var otherGlobalDifferentCompartment = newGlobal(); eval = otherGlobalDifferentCompartment.eval; res = new f(); assertEq(res[0] !== res[1], true); assertEq(res[0] !== this, true); assertEq(res[0] instanceof f, true); assertEq(res[1], otherGlobalDifferentCompartment); res = f(); assertEq(res[0] !== res[1], true); assertEq(res[0], this); assertEq(res[1], otherGlobalDifferentCompartment); /******************************************************************************/ if (typeof reportCompare === "function") reportCompare(true, true); print("All tests passed!");
f
identifier_name
cross-global-eval-is-indirect.js
// |reftest| skip-if(!xulRuntime.shell) -- needs newGlobal() /* * Any copyright is dedicated to the Public Domain. * http://creativecommons.org/licenses/publicdomain/ */ //----------------------------------------------------------------------------- var BUGNUMBER = 608473; var summary = '|var eval = otherWindow.eval; eval(...)| should behave like indirectly ' + 'calling that eval from a script in that other window'; print(BUGNUMBER + ": " + summary); /************** * BEGIN TEST * **************/ var originalEval = eval; var res; function f()
var otherGlobalSameCompartment = newGlobal("same-compartment"); eval = otherGlobalSameCompartment.eval; res = new f(); assertEq(res[0] !== res[1], true); assertEq(res[0] !== this, true); assertEq(res[0] instanceof f, true); assertEq(res[1], otherGlobalSameCompartment); res = f(); assertEq(res[0] !== res[1], true); assertEq(res[0], this); assertEq(res[1], otherGlobalSameCompartment); var otherGlobalDifferentCompartment = newGlobal(); eval = otherGlobalDifferentCompartment.eval; res = new f(); assertEq(res[0] !== res[1], true); assertEq(res[0] !== this, true); assertEq(res[0] instanceof f, true); assertEq(res[1], otherGlobalDifferentCompartment); res = f(); assertEq(res[0] !== res[1], true); assertEq(res[0], this); assertEq(res[1], otherGlobalDifferentCompartment); /******************************************************************************/ if (typeof reportCompare === "function") reportCompare(true, true); print("All tests passed!");
{ return [this, eval("this")]; }
identifier_body
lithos_switch.rs
extern crate libc; extern crate nix; extern crate env_logger; extern crate regex; extern crate argparse; extern crate quire; #[macro_use] extern crate log; extern crate lithos; use std::env; use std::io::{stderr, Read, Write}; use std::process::exit; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::fs::{File}; use std::fs::{copy, rename}; use std::process::{Command, Stdio}; use argparse::{ArgumentParser, Parse, StoreTrue, Print}; use quire::{parse_config, Options}; use nix::sys::signal::{SIGQUIT, kill}; use nix::unistd::Pid; use lithos::master_config::MasterConfig; use lithos::sandbox_config::SandboxConfig; fn switch_config(master_cfg: &Path, sandbox_name: String, config_file: &Path) -> Result<(), String> { match Command::new(env::current_exe().unwrap() .parent().unwrap().join("lithos_check")) .stdin(Stdio::inherit()) .stdout(Stdio::inherit()) .stderr(Stdio::inherit()) .arg("--config") .arg(&master_cfg) .arg("--sandbox") .arg(&sandbox_name) .arg("--alternate-config") .arg(&config_file) .output() { Ok(ref po) if po.status.code() == Some(0) => { } Ok(ref po) => { return Err(format!( "Configuration check failed with exit status: {}", po.status)); } Err(e) => { return Err(format!("Can't check configuration: {}", e)); } } info!("Checked. Proceeding"); let master: MasterConfig = match parse_config(&master_cfg, &MasterConfig::validator(), &Options::default()) { Ok(cfg) => cfg, Err(e) =>
}; let sandbox_fn = master_cfg.parent().unwrap() .join(&master.sandboxes_dir) .join(&(sandbox_name.clone() + ".yaml")); let sandbox: SandboxConfig = match parse_config(&sandbox_fn, &SandboxConfig::validator(), &Options::default()) { Ok(cfg) => cfg, Err(e) => { return Err(format!("Can't parse sandbox config: {}", e)); } }; let target_fn = master_cfg.parent().unwrap() .join(&master.processes_dir) .join(sandbox.config_file.as_ref().unwrap_or( &PathBuf::from(&(sandbox_name.clone() + ".yaml")))); debug!("Target filename {:?}", target_fn); let tmp_filename = target_fn.with_file_name( &format!(".tmp.{}", sandbox_name)); try!(copy(&config_file, &tmp_filename) .map_err(|e| format!("Error copying: {}", e))); try!(rename(&tmp_filename, &target_fn) .map_err(|e| format!("Error replacing file: {}", e))); info!("Done. Sending SIGQUIT to lithos_tree"); let pid_file = master.runtime_dir.join("master.pid"); let mut buf = String::with_capacity(50); let read_pid = File::open(&pid_file) .and_then(|mut f| f.read_to_string(&mut buf)) .ok() .and_then(|_| FromStr::from_str(buf[..].trim()).ok()) .map(Pid::from_raw); match read_pid { Some(pid) if kill(pid, None).is_ok() => { kill(pid, SIGQUIT) .map_err(|e| error!("Error sending QUIT to master: {:?}", e)).ok(); } Some(pid) => { warn!("Process with pid {} is not running...", pid); } None => { warn!("Can't read pid file {}. Probably daemon is not running.", pid_file.display()); } }; return Ok(()); } fn main() { if env::var("RUST_LOG").is_err() { env::set_var("RUST_LOG", "warn"); } env_logger::init(); let mut master_config = PathBuf::from("/etc/lithos/master.yaml"); let mut verbose = false; let mut config_file = PathBuf::from(""); let mut sandbox_name = "".to_string(); { let mut ap = ArgumentParser::new(); ap.set_description("Checks if lithos configuration is ok"); ap.refer(&mut master_config) .add_option(&["--master"], Parse, "Name of the master configuration file \ (default /etc/lithos/master.yaml)") .metavar("FILE"); ap.refer(&mut verbose) .add_option(&["-v", "--verbose"], StoreTrue, "Verbose configuration"); ap.refer(&mut sandbox_name) .add_argument("sandbox", Parse, "Name of the sandbox which configuration will be switched for") .required() .metavar("NAME"); ap.refer(&mut config_file) .add_argument("new_config", Parse, " Name of the process configuration file for this sandbox to switch to. The file is copied over current config after configuration is validated and just before sending a signal to lithos_tree.") .metavar("FILE") .required(); ap.add_option(&["--version"], Print(env!("CARGO_PKG_VERSION").to_string()), "Show version"); match ap.parse_args() { Ok(()) => {} Err(x) => { exit(x); } } } match switch_config(&master_config, sandbox_name, &config_file) { Ok(()) => { exit(0); } Err(e) => { write!(&mut stderr(), "Fatal error: {}\n", e).unwrap(); exit(1); } } }
{ return Err(format!("Can't parse master config: {}", e)); }
conditional_block
lithos_switch.rs
extern crate libc; extern crate nix; extern crate env_logger; extern crate regex; extern crate argparse; extern crate quire; #[macro_use] extern crate log; extern crate lithos; use std::env; use std::io::{stderr, Read, Write}; use std::process::exit; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::fs::{File}; use std::fs::{copy, rename}; use std::process::{Command, Stdio}; use argparse::{ArgumentParser, Parse, StoreTrue, Print}; use quire::{parse_config, Options}; use nix::sys::signal::{SIGQUIT, kill}; use nix::unistd::Pid; use lithos::master_config::MasterConfig; use lithos::sandbox_config::SandboxConfig; fn switch_config(master_cfg: &Path, sandbox_name: String, config_file: &Path) -> Result<(), String> { match Command::new(env::current_exe().unwrap() .parent().unwrap().join("lithos_check")) .stdin(Stdio::inherit()) .stdout(Stdio::inherit()) .stderr(Stdio::inherit()) .arg("--config") .arg(&master_cfg) .arg("--sandbox") .arg(&sandbox_name) .arg("--alternate-config") .arg(&config_file) .output() { Ok(ref po) if po.status.code() == Some(0) => { } Ok(ref po) => { return Err(format!( "Configuration check failed with exit status: {}", po.status)); } Err(e) => { return Err(format!("Can't check configuration: {}", e)); } } info!("Checked. Proceeding"); let master: MasterConfig = match parse_config(&master_cfg, &MasterConfig::validator(), &Options::default()) { Ok(cfg) => cfg, Err(e) => { return Err(format!("Can't parse master config: {}", e)); } }; let sandbox_fn = master_cfg.parent().unwrap() .join(&master.sandboxes_dir) .join(&(sandbox_name.clone() + ".yaml")); let sandbox: SandboxConfig = match parse_config(&sandbox_fn, &SandboxConfig::validator(), &Options::default()) { Ok(cfg) => cfg, Err(e) => { return Err(format!("Can't parse sandbox config: {}", e)); } }; let target_fn = master_cfg.parent().unwrap() .join(&master.processes_dir) .join(sandbox.config_file.as_ref().unwrap_or( &PathBuf::from(&(sandbox_name.clone() + ".yaml")))); debug!("Target filename {:?}", target_fn); let tmp_filename = target_fn.with_file_name( &format!(".tmp.{}", sandbox_name)); try!(copy(&config_file, &tmp_filename) .map_err(|e| format!("Error copying: {}", e))); try!(rename(&tmp_filename, &target_fn) .map_err(|e| format!("Error replacing file: {}", e))); info!("Done. Sending SIGQUIT to lithos_tree"); let pid_file = master.runtime_dir.join("master.pid"); let mut buf = String::with_capacity(50); let read_pid = File::open(&pid_file) .and_then(|mut f| f.read_to_string(&mut buf)) .ok() .and_then(|_| FromStr::from_str(buf[..].trim()).ok()) .map(Pid::from_raw); match read_pid { Some(pid) if kill(pid, None).is_ok() => { kill(pid, SIGQUIT) .map_err(|e| error!("Error sending QUIT to master: {:?}", e)).ok(); } Some(pid) => { warn!("Process with pid {} is not running...", pid);
pid_file.display()); } }; return Ok(()); } fn main() { if env::var("RUST_LOG").is_err() { env::set_var("RUST_LOG", "warn"); } env_logger::init(); let mut master_config = PathBuf::from("/etc/lithos/master.yaml"); let mut verbose = false; let mut config_file = PathBuf::from(""); let mut sandbox_name = "".to_string(); { let mut ap = ArgumentParser::new(); ap.set_description("Checks if lithos configuration is ok"); ap.refer(&mut master_config) .add_option(&["--master"], Parse, "Name of the master configuration file \ (default /etc/lithos/master.yaml)") .metavar("FILE"); ap.refer(&mut verbose) .add_option(&["-v", "--verbose"], StoreTrue, "Verbose configuration"); ap.refer(&mut sandbox_name) .add_argument("sandbox", Parse, "Name of the sandbox which configuration will be switched for") .required() .metavar("NAME"); ap.refer(&mut config_file) .add_argument("new_config", Parse, " Name of the process configuration file for this sandbox to switch to. The file is copied over current config after configuration is validated and just before sending a signal to lithos_tree.") .metavar("FILE") .required(); ap.add_option(&["--version"], Print(env!("CARGO_PKG_VERSION").to_string()), "Show version"); match ap.parse_args() { Ok(()) => {} Err(x) => { exit(x); } } } match switch_config(&master_config, sandbox_name, &config_file) { Ok(()) => { exit(0); } Err(e) => { write!(&mut stderr(), "Fatal error: {}\n", e).unwrap(); exit(1); } } }
} None => { warn!("Can't read pid file {}. Probably daemon is not running.",
random_line_split
lithos_switch.rs
extern crate libc; extern crate nix; extern crate env_logger; extern crate regex; extern crate argparse; extern crate quire; #[macro_use] extern crate log; extern crate lithos; use std::env; use std::io::{stderr, Read, Write}; use std::process::exit; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::fs::{File}; use std::fs::{copy, rename}; use std::process::{Command, Stdio}; use argparse::{ArgumentParser, Parse, StoreTrue, Print}; use quire::{parse_config, Options}; use nix::sys::signal::{SIGQUIT, kill}; use nix::unistd::Pid; use lithos::master_config::MasterConfig; use lithos::sandbox_config::SandboxConfig; fn switch_config(master_cfg: &Path, sandbox_name: String, config_file: &Path) -> Result<(), String> { match Command::new(env::current_exe().unwrap() .parent().unwrap().join("lithos_check")) .stdin(Stdio::inherit()) .stdout(Stdio::inherit()) .stderr(Stdio::inherit()) .arg("--config") .arg(&master_cfg) .arg("--sandbox") .arg(&sandbox_name) .arg("--alternate-config") .arg(&config_file) .output() { Ok(ref po) if po.status.code() == Some(0) => { } Ok(ref po) => { return Err(format!( "Configuration check failed with exit status: {}", po.status)); } Err(e) => { return Err(format!("Can't check configuration: {}", e)); } } info!("Checked. Proceeding"); let master: MasterConfig = match parse_config(&master_cfg, &MasterConfig::validator(), &Options::default()) { Ok(cfg) => cfg, Err(e) => { return Err(format!("Can't parse master config: {}", e)); } }; let sandbox_fn = master_cfg.parent().unwrap() .join(&master.sandboxes_dir) .join(&(sandbox_name.clone() + ".yaml")); let sandbox: SandboxConfig = match parse_config(&sandbox_fn, &SandboxConfig::validator(), &Options::default()) { Ok(cfg) => cfg, Err(e) => { return Err(format!("Can't parse sandbox config: {}", e)); } }; let target_fn = master_cfg.parent().unwrap() .join(&master.processes_dir) .join(sandbox.config_file.as_ref().unwrap_or( &PathBuf::from(&(sandbox_name.clone() + ".yaml")))); debug!("Target filename {:?}", target_fn); let tmp_filename = target_fn.with_file_name( &format!(".tmp.{}", sandbox_name)); try!(copy(&config_file, &tmp_filename) .map_err(|e| format!("Error copying: {}", e))); try!(rename(&tmp_filename, &target_fn) .map_err(|e| format!("Error replacing file: {}", e))); info!("Done. Sending SIGQUIT to lithos_tree"); let pid_file = master.runtime_dir.join("master.pid"); let mut buf = String::with_capacity(50); let read_pid = File::open(&pid_file) .and_then(|mut f| f.read_to_string(&mut buf)) .ok() .and_then(|_| FromStr::from_str(buf[..].trim()).ok()) .map(Pid::from_raw); match read_pid { Some(pid) if kill(pid, None).is_ok() => { kill(pid, SIGQUIT) .map_err(|e| error!("Error sending QUIT to master: {:?}", e)).ok(); } Some(pid) => { warn!("Process with pid {} is not running...", pid); } None => { warn!("Can't read pid file {}. Probably daemon is not running.", pid_file.display()); } }; return Ok(()); } fn main()
{ if env::var("RUST_LOG").is_err() { env::set_var("RUST_LOG", "warn"); } env_logger::init(); let mut master_config = PathBuf::from("/etc/lithos/master.yaml"); let mut verbose = false; let mut config_file = PathBuf::from(""); let mut sandbox_name = "".to_string(); { let mut ap = ArgumentParser::new(); ap.set_description("Checks if lithos configuration is ok"); ap.refer(&mut master_config) .add_option(&["--master"], Parse, "Name of the master configuration file \ (default /etc/lithos/master.yaml)") .metavar("FILE"); ap.refer(&mut verbose) .add_option(&["-v", "--verbose"], StoreTrue, "Verbose configuration"); ap.refer(&mut sandbox_name) .add_argument("sandbox", Parse, "Name of the sandbox which configuration will be switched for") .required() .metavar("NAME"); ap.refer(&mut config_file) .add_argument("new_config", Parse, " Name of the process configuration file for this sandbox to switch to. The file is copied over current config after configuration is validated and just before sending a signal to lithos_tree.") .metavar("FILE") .required(); ap.add_option(&["--version"], Print(env!("CARGO_PKG_VERSION").to_string()), "Show version"); match ap.parse_args() { Ok(()) => {} Err(x) => { exit(x); } } } match switch_config(&master_config, sandbox_name, &config_file) { Ok(()) => { exit(0); } Err(e) => { write!(&mut stderr(), "Fatal error: {}\n", e).unwrap(); exit(1); } } }
identifier_body
lithos_switch.rs
extern crate libc; extern crate nix; extern crate env_logger; extern crate regex; extern crate argparse; extern crate quire; #[macro_use] extern crate log; extern crate lithos; use std::env; use std::io::{stderr, Read, Write}; use std::process::exit; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::fs::{File}; use std::fs::{copy, rename}; use std::process::{Command, Stdio}; use argparse::{ArgumentParser, Parse, StoreTrue, Print}; use quire::{parse_config, Options}; use nix::sys::signal::{SIGQUIT, kill}; use nix::unistd::Pid; use lithos::master_config::MasterConfig; use lithos::sandbox_config::SandboxConfig; fn switch_config(master_cfg: &Path, sandbox_name: String, config_file: &Path) -> Result<(), String> { match Command::new(env::current_exe().unwrap() .parent().unwrap().join("lithos_check")) .stdin(Stdio::inherit()) .stdout(Stdio::inherit()) .stderr(Stdio::inherit()) .arg("--config") .arg(&master_cfg) .arg("--sandbox") .arg(&sandbox_name) .arg("--alternate-config") .arg(&config_file) .output() { Ok(ref po) if po.status.code() == Some(0) => { } Ok(ref po) => { return Err(format!( "Configuration check failed with exit status: {}", po.status)); } Err(e) => { return Err(format!("Can't check configuration: {}", e)); } } info!("Checked. Proceeding"); let master: MasterConfig = match parse_config(&master_cfg, &MasterConfig::validator(), &Options::default()) { Ok(cfg) => cfg, Err(e) => { return Err(format!("Can't parse master config: {}", e)); } }; let sandbox_fn = master_cfg.parent().unwrap() .join(&master.sandboxes_dir) .join(&(sandbox_name.clone() + ".yaml")); let sandbox: SandboxConfig = match parse_config(&sandbox_fn, &SandboxConfig::validator(), &Options::default()) { Ok(cfg) => cfg, Err(e) => { return Err(format!("Can't parse sandbox config: {}", e)); } }; let target_fn = master_cfg.parent().unwrap() .join(&master.processes_dir) .join(sandbox.config_file.as_ref().unwrap_or( &PathBuf::from(&(sandbox_name.clone() + ".yaml")))); debug!("Target filename {:?}", target_fn); let tmp_filename = target_fn.with_file_name( &format!(".tmp.{}", sandbox_name)); try!(copy(&config_file, &tmp_filename) .map_err(|e| format!("Error copying: {}", e))); try!(rename(&tmp_filename, &target_fn) .map_err(|e| format!("Error replacing file: {}", e))); info!("Done. Sending SIGQUIT to lithos_tree"); let pid_file = master.runtime_dir.join("master.pid"); let mut buf = String::with_capacity(50); let read_pid = File::open(&pid_file) .and_then(|mut f| f.read_to_string(&mut buf)) .ok() .and_then(|_| FromStr::from_str(buf[..].trim()).ok()) .map(Pid::from_raw); match read_pid { Some(pid) if kill(pid, None).is_ok() => { kill(pid, SIGQUIT) .map_err(|e| error!("Error sending QUIT to master: {:?}", e)).ok(); } Some(pid) => { warn!("Process with pid {} is not running...", pid); } None => { warn!("Can't read pid file {}. Probably daemon is not running.", pid_file.display()); } }; return Ok(()); } fn
() { if env::var("RUST_LOG").is_err() { env::set_var("RUST_LOG", "warn"); } env_logger::init(); let mut master_config = PathBuf::from("/etc/lithos/master.yaml"); let mut verbose = false; let mut config_file = PathBuf::from(""); let mut sandbox_name = "".to_string(); { let mut ap = ArgumentParser::new(); ap.set_description("Checks if lithos configuration is ok"); ap.refer(&mut master_config) .add_option(&["--master"], Parse, "Name of the master configuration file \ (default /etc/lithos/master.yaml)") .metavar("FILE"); ap.refer(&mut verbose) .add_option(&["-v", "--verbose"], StoreTrue, "Verbose configuration"); ap.refer(&mut sandbox_name) .add_argument("sandbox", Parse, "Name of the sandbox which configuration will be switched for") .required() .metavar("NAME"); ap.refer(&mut config_file) .add_argument("new_config", Parse, " Name of the process configuration file for this sandbox to switch to. The file is copied over current config after configuration is validated and just before sending a signal to lithos_tree.") .metavar("FILE") .required(); ap.add_option(&["--version"], Print(env!("CARGO_PKG_VERSION").to_string()), "Show version"); match ap.parse_args() { Ok(()) => {} Err(x) => { exit(x); } } } match switch_config(&master_config, sandbox_name, &config_file) { Ok(()) => { exit(0); } Err(e) => { write!(&mut stderr(), "Fatal error: {}\n", e).unwrap(); exit(1); } } }
main
identifier_name
tests.py
import datetime from django.conf import settings from django.db import DEFAULT_DB_ALIAS from django.test import TestCase, skipIfDBFeature from django.utils import tzinfo from models import Donut, RumBaba class DataTypesTestCase(TestCase): def test_boolean_type(self): d = Donut(name='Apple Fritter') self.assertFalse(d.is_frosted) self.assertTrue(d.has_sprinkles is None) d.has_sprinkles = True self.assertTrue(d.has_sprinkles) d.save() d2 = Donut.objects.get(name='Apple Fritter') self.assertFalse(d2.is_frosted) self.assertTrue(d2.has_sprinkles) def test_date_type(self): d = Donut(name='Apple Fritter') d.baked_date = datetime.date(year=1938, month=6, day=4) d.baked_time = datetime.time(hour=5, minute=30) d.consumed_at = datetime.datetime(year=2007, month=4, day=20, hour=16, minute=19, second=59) d.save() d2 = Donut.objects.get(name='Apple Fritter') self.assertEqual(d2.baked_date, datetime.date(1938, 6, 4)) self.assertEqual(d2.baked_time, datetime.time(5, 30)) self.assertEqual(d2.consumed_at, datetime.datetime(2007, 4, 20, 16, 19, 59)) def test_time_field(self): #Test for ticket #12059: TimeField wrongly handling datetime.datetime object. d = Donut(name='Apple Fritter') d.baked_time = datetime.datetime(year=2007, month=4, day=20, hour=16, minute=19, second=59) d.save() d2 = Donut.objects.get(name='Apple Fritter') self.assertEqual(d2.baked_time, datetime.time(16, 19, 59)) def test_year_boundaries(self): """Year boundary tests (ticket #3689)""" d = Donut.objects.create(name='Date Test 2007', baked_date=datetime.datetime(year=2007, month=12, day=31), consumed_at=datetime.datetime(year=2007, month=12, day=31, hour=23, minute=59, second=59)) d1 = Donut.objects.create(name='Date Test 2006', baked_date=datetime.datetime(year=2006, month=1, day=1), consumed_at=datetime.datetime(year=2006, month=1, day=1)) self.assertEqual("Date Test 2007", Donut.objects.filter(baked_date__year=2007)[0].name) self.assertEqual("Date Test 2006", Donut.objects.filter(baked_date__year=2006)[0].name) d2 = Donut.objects.create(name='Apple Fritter', consumed_at = datetime.datetime(year=2007, month=4, day=20, hour=16, minute=19, second=59)) self.assertEqual([u'Apple Fritter', u'Date Test 2007'], list(Donut.objects.filter(consumed_at__year=2007).order_by('name').values_list('name', flat=True))) self.assertEqual(0, Donut.objects.filter(consumed_at__year=2005).count()) self.assertEqual(0, Donut.objects.filter(consumed_at__year=2008).count()) def test_textfields_unicode(self):
@skipIfDBFeature('supports_timezones') def test_error_on_timezone(self): """Regression test for #8354: the MySQL and Oracle backends should raise an error if given a timezone-aware datetime object.""" dt = datetime.datetime(2008, 8, 31, 16, 20, tzinfo=tzinfo.FixedOffset(0)) d = Donut(name='Bear claw', consumed_at=dt) self.assertRaises(ValueError, d.save) # ValueError: MySQL backend does not support timezone-aware datetimes. def test_datefield_auto_now_add(self): """Regression test for #10970, auto_now_add for DateField should store a Python datetime.date, not a datetime.datetime""" b = RumBaba.objects.create() # Verify we didn't break DateTimeField behavior self.assert_(isinstance(b.baked_timestamp, datetime.datetime)) # We need to test this this way because datetime.datetime inherits # from datetime.date: self.assert_(isinstance(b.baked_date, datetime.date) and not isinstance(b.baked_date, datetime.datetime))
"""Regression test for #10238: TextField values returned from the database should be unicode.""" d = Donut.objects.create(name=u'Jelly Donut', review=u'Outstanding') newd = Donut.objects.get(id=d.id) self.assert_(isinstance(newd.review, unicode))
identifier_body
tests.py
import datetime from django.conf import settings from django.db import DEFAULT_DB_ALIAS from django.test import TestCase, skipIfDBFeature from django.utils import tzinfo from models import Donut, RumBaba class DataTypesTestCase(TestCase): def test_boolean_type(self): d = Donut(name='Apple Fritter') self.assertFalse(d.is_frosted) self.assertTrue(d.has_sprinkles is None) d.has_sprinkles = True self.assertTrue(d.has_sprinkles) d.save() d2 = Donut.objects.get(name='Apple Fritter') self.assertFalse(d2.is_frosted) self.assertTrue(d2.has_sprinkles) def test_date_type(self): d = Donut(name='Apple Fritter') d.baked_date = datetime.date(year=1938, month=6, day=4) d.baked_time = datetime.time(hour=5, minute=30) d.consumed_at = datetime.datetime(year=2007, month=4, day=20, hour=16, minute=19, second=59) d.save() d2 = Donut.objects.get(name='Apple Fritter') self.assertEqual(d2.baked_date, datetime.date(1938, 6, 4)) self.assertEqual(d2.baked_time, datetime.time(5, 30)) self.assertEqual(d2.consumed_at, datetime.datetime(2007, 4, 20, 16, 19, 59)) def test_time_field(self): #Test for ticket #12059: TimeField wrongly handling datetime.datetime object. d = Donut(name='Apple Fritter') d.baked_time = datetime.datetime(year=2007, month=4, day=20, hour=16, minute=19, second=59) d.save() d2 = Donut.objects.get(name='Apple Fritter') self.assertEqual(d2.baked_time, datetime.time(16, 19, 59)) def
(self): """Year boundary tests (ticket #3689)""" d = Donut.objects.create(name='Date Test 2007', baked_date=datetime.datetime(year=2007, month=12, day=31), consumed_at=datetime.datetime(year=2007, month=12, day=31, hour=23, minute=59, second=59)) d1 = Donut.objects.create(name='Date Test 2006', baked_date=datetime.datetime(year=2006, month=1, day=1), consumed_at=datetime.datetime(year=2006, month=1, day=1)) self.assertEqual("Date Test 2007", Donut.objects.filter(baked_date__year=2007)[0].name) self.assertEqual("Date Test 2006", Donut.objects.filter(baked_date__year=2006)[0].name) d2 = Donut.objects.create(name='Apple Fritter', consumed_at = datetime.datetime(year=2007, month=4, day=20, hour=16, minute=19, second=59)) self.assertEqual([u'Apple Fritter', u'Date Test 2007'], list(Donut.objects.filter(consumed_at__year=2007).order_by('name').values_list('name', flat=True))) self.assertEqual(0, Donut.objects.filter(consumed_at__year=2005).count()) self.assertEqual(0, Donut.objects.filter(consumed_at__year=2008).count()) def test_textfields_unicode(self): """Regression test for #10238: TextField values returned from the database should be unicode.""" d = Donut.objects.create(name=u'Jelly Donut', review=u'Outstanding') newd = Donut.objects.get(id=d.id) self.assert_(isinstance(newd.review, unicode)) @skipIfDBFeature('supports_timezones') def test_error_on_timezone(self): """Regression test for #8354: the MySQL and Oracle backends should raise an error if given a timezone-aware datetime object.""" dt = datetime.datetime(2008, 8, 31, 16, 20, tzinfo=tzinfo.FixedOffset(0)) d = Donut(name='Bear claw', consumed_at=dt) self.assertRaises(ValueError, d.save) # ValueError: MySQL backend does not support timezone-aware datetimes. def test_datefield_auto_now_add(self): """Regression test for #10970, auto_now_add for DateField should store a Python datetime.date, not a datetime.datetime""" b = RumBaba.objects.create() # Verify we didn't break DateTimeField behavior self.assert_(isinstance(b.baked_timestamp, datetime.datetime)) # We need to test this this way because datetime.datetime inherits # from datetime.date: self.assert_(isinstance(b.baked_date, datetime.date) and not isinstance(b.baked_date, datetime.datetime))
test_year_boundaries
identifier_name
tests.py
import datetime from django.conf import settings from django.db import DEFAULT_DB_ALIAS from django.test import TestCase, skipIfDBFeature from django.utils import tzinfo from models import Donut, RumBaba class DataTypesTestCase(TestCase): def test_boolean_type(self): d = Donut(name='Apple Fritter') self.assertFalse(d.is_frosted) self.assertTrue(d.has_sprinkles is None) d.has_sprinkles = True
d2 = Donut.objects.get(name='Apple Fritter') self.assertFalse(d2.is_frosted) self.assertTrue(d2.has_sprinkles) def test_date_type(self): d = Donut(name='Apple Fritter') d.baked_date = datetime.date(year=1938, month=6, day=4) d.baked_time = datetime.time(hour=5, minute=30) d.consumed_at = datetime.datetime(year=2007, month=4, day=20, hour=16, minute=19, second=59) d.save() d2 = Donut.objects.get(name='Apple Fritter') self.assertEqual(d2.baked_date, datetime.date(1938, 6, 4)) self.assertEqual(d2.baked_time, datetime.time(5, 30)) self.assertEqual(d2.consumed_at, datetime.datetime(2007, 4, 20, 16, 19, 59)) def test_time_field(self): #Test for ticket #12059: TimeField wrongly handling datetime.datetime object. d = Donut(name='Apple Fritter') d.baked_time = datetime.datetime(year=2007, month=4, day=20, hour=16, minute=19, second=59) d.save() d2 = Donut.objects.get(name='Apple Fritter') self.assertEqual(d2.baked_time, datetime.time(16, 19, 59)) def test_year_boundaries(self): """Year boundary tests (ticket #3689)""" d = Donut.objects.create(name='Date Test 2007', baked_date=datetime.datetime(year=2007, month=12, day=31), consumed_at=datetime.datetime(year=2007, month=12, day=31, hour=23, minute=59, second=59)) d1 = Donut.objects.create(name='Date Test 2006', baked_date=datetime.datetime(year=2006, month=1, day=1), consumed_at=datetime.datetime(year=2006, month=1, day=1)) self.assertEqual("Date Test 2007", Donut.objects.filter(baked_date__year=2007)[0].name) self.assertEqual("Date Test 2006", Donut.objects.filter(baked_date__year=2006)[0].name) d2 = Donut.objects.create(name='Apple Fritter', consumed_at = datetime.datetime(year=2007, month=4, day=20, hour=16, minute=19, second=59)) self.assertEqual([u'Apple Fritter', u'Date Test 2007'], list(Donut.objects.filter(consumed_at__year=2007).order_by('name').values_list('name', flat=True))) self.assertEqual(0, Donut.objects.filter(consumed_at__year=2005).count()) self.assertEqual(0, Donut.objects.filter(consumed_at__year=2008).count()) def test_textfields_unicode(self): """Regression test for #10238: TextField values returned from the database should be unicode.""" d = Donut.objects.create(name=u'Jelly Donut', review=u'Outstanding') newd = Donut.objects.get(id=d.id) self.assert_(isinstance(newd.review, unicode)) @skipIfDBFeature('supports_timezones') def test_error_on_timezone(self): """Regression test for #8354: the MySQL and Oracle backends should raise an error if given a timezone-aware datetime object.""" dt = datetime.datetime(2008, 8, 31, 16, 20, tzinfo=tzinfo.FixedOffset(0)) d = Donut(name='Bear claw', consumed_at=dt) self.assertRaises(ValueError, d.save) # ValueError: MySQL backend does not support timezone-aware datetimes. def test_datefield_auto_now_add(self): """Regression test for #10970, auto_now_add for DateField should store a Python datetime.date, not a datetime.datetime""" b = RumBaba.objects.create() # Verify we didn't break DateTimeField behavior self.assert_(isinstance(b.baked_timestamp, datetime.datetime)) # We need to test this this way because datetime.datetime inherits # from datetime.date: self.assert_(isinstance(b.baked_date, datetime.date) and not isinstance(b.baked_date, datetime.datetime))
self.assertTrue(d.has_sprinkles) d.save()
random_line_split
fs.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use os::unix::prelude::*; use ffi::{OsString, OsStr}; use fmt; use io::{self, Error, ErrorKind, SeekFrom}; use path::{Path, PathBuf}; use sync::Arc; use sys::fd::FileDesc; use sys::time::SystemTime; use sys::{cvt, syscall}; use sys_common::{AsInner, FromInner}; pub struct File(FileDesc); #[derive(Clone)] pub struct FileAttr { stat: syscall::Stat, } pub struct ReadDir { data: Vec<u8>, i: usize, root: Arc<PathBuf>, } struct Dir(FileDesc); unsafe impl Send for Dir {} unsafe impl Sync for Dir {} pub struct DirEntry { root: Arc<PathBuf>, name: Box<[u8]> } #[derive(Clone, Debug)] pub struct OpenOptions { // generic read: bool, write: bool, append: bool, truncate: bool, create: bool, create_new: bool, // system-specific custom_flags: i32, mode: u16, } #[derive(Clone, PartialEq, Eq, Debug)] pub struct FilePermissions { mode: u16 } #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] pub struct FileType { mode: u16 } #[derive(Debug)] pub struct DirBuilder { mode: u16 } impl FileAttr { pub fn size(&self) -> u64 { self.stat.st_size as u64 } pub fn perm(&self) -> FilePermissions { FilePermissions { mode: (self.stat.st_mode as u16) & 0o777 } } pub fn file_type(&self) -> FileType { FileType { mode: self.stat.st_mode as u16 } } } impl FileAttr { pub fn modified(&self) -> io::Result<SystemTime> { Ok(SystemTime::from(syscall::TimeSpec { tv_sec: self.stat.st_mtime as i64, tv_nsec: self.stat.st_mtime_nsec as i32, })) } pub fn accessed(&self) -> io::Result<SystemTime> { Ok(SystemTime::from(syscall::TimeSpec { tv_sec: self.stat.st_atime as i64, tv_nsec: self.stat.st_atime_nsec as i32, })) } pub fn created(&self) -> io::Result<SystemTime> { Ok(SystemTime::from(syscall::TimeSpec { tv_sec: self.stat.st_ctime as i64, tv_nsec: self.stat.st_ctime_nsec as i32, })) } } impl AsInner<syscall::Stat> for FileAttr { fn as_inner(&self) -> &syscall::Stat { &self.stat } } impl FilePermissions { pub fn readonly(&self) -> bool { self.mode & 0o222 == 0 } pub fn set_readonly(&mut self, readonly: bool) { if readonly { self.mode &= !0o222; } else { self.mode |= 0o222; } } pub fn mode(&self) -> u32 { self.mode as u32 } } impl FileType { pub fn is_dir(&self) -> bool { self.is(syscall::MODE_DIR) } pub fn is_file(&self) -> bool { self.is(syscall::MODE_FILE) } pub fn is_symlink(&self) -> bool { self.is(syscall::MODE_SYMLINK) } pub fn is(&self, mode: u16) -> bool { self.mode & syscall::MODE_TYPE == mode } } impl FromInner<u32> for FilePermissions { fn from_inner(mode: u32) -> FilePermissions { FilePermissions { mode: mode as u16 } } } impl fmt::Debug for ReadDir { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame. // Thus the result will be e g 'ReadDir("/home")' fmt::Debug::fmt(&*self.root, f) } } impl Iterator for ReadDir { type Item = io::Result<DirEntry>; fn next(&mut self) -> Option<io::Result<DirEntry>> { loop { let start = self.i; let mut i = self.i; while i < self.data.len() { self.i += 1; if self.data[i] == b'\n' { break; } i += 1; } if start < self.i { let ret = DirEntry { name: self.data[start .. i].to_owned().into_boxed_slice(), root: self.root.clone() }; if ret.name_bytes() != b"." && ret.name_bytes() != b".." { return Some(Ok(ret)) } } else { return None; } } } } impl DirEntry { pub fn path(&self) -> PathBuf { self.root.join(OsStr::from_bytes(self.name_bytes())) } pub fn file_name(&self) -> OsString { OsStr::from_bytes(self.name_bytes()).to_os_string() } pub fn metadata(&self) -> io::Result<FileAttr> { lstat(&self.path()) } pub fn file_type(&self) -> io::Result<FileType> { lstat(&self.path()).map(|m| m.file_type()) } fn name_bytes(&self) -> &[u8] { &*self.name } } impl OpenOptions { pub fn new() -> OpenOptions { OpenOptions { // generic read: false, write: false, append: false, truncate: false, create: false, create_new: false, // system-specific custom_flags: 0, mode: 0o666, } } pub fn read(&mut self, read: bool) { self.read = read; } pub fn write(&mut self, write: bool) { self.write = write; } pub fn append(&mut self, append: bool) { self.append = append; } pub fn truncate(&mut self, truncate: bool) { self.truncate = truncate; } pub fn create(&mut self, create: bool) { self.create = create; } pub fn create_new(&mut self, create_new: bool) { self.create_new = create_new; } pub fn custom_flags(&mut self, flags: i32) { self.custom_flags = flags; } pub fn mode(&mut self, mode: u32) { self.mode = mode as u16; } fn get_access_mode(&self) -> io::Result<usize> { match (self.read, self.write, self.append) { (true, false, false) => Ok(syscall::O_RDONLY), (false, true, false) => Ok(syscall::O_WRONLY), (true, true, false) => Ok(syscall::O_RDWR), (false, _, true) => Ok(syscall::O_WRONLY | syscall::O_APPEND), (true, _, true) => Ok(syscall::O_RDWR | syscall::O_APPEND), (false, false, false) => Err(Error::from_raw_os_error(syscall::EINVAL)), } } fn get_creation_mode(&self) -> io::Result<usize> { match (self.write, self.append) { (true, false) => {} (false, false) => if self.truncate || self.create || self.create_new { return Err(Error::from_raw_os_error(syscall::EINVAL)); }, (_, true) => if self.truncate && !self.create_new { return Err(Error::from_raw_os_error(syscall::EINVAL)); }, } Ok(match (self.create, self.truncate, self.create_new) { (false, false, false) => 0, (true, false, false) => syscall::O_CREAT, (false, true, false) => syscall::O_TRUNC, (true, true, false) => syscall::O_CREAT | syscall::O_TRUNC, (_, _, true) => syscall::O_CREAT | syscall::O_EXCL, }) } } impl File { pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> { let flags = syscall::O_CLOEXEC | opts.get_access_mode()? as usize | opts.get_creation_mode()? as usize | (opts.custom_flags as usize & !syscall::O_ACCMODE); let fd = cvt(syscall::open(path.to_str().unwrap(), flags | opts.mode as usize))?; Ok(File(FileDesc::new(fd))) } pub fn file_attr(&self) -> io::Result<FileAttr> { let mut stat = syscall::Stat::default(); cvt(syscall::fstat(self.0.raw(), &mut stat))?; Ok(FileAttr { stat: stat }) } pub fn fsync(&self) -> io::Result<()> { cvt(syscall::fsync(self.0.raw()))?; Ok(()) } pub fn datasync(&self) -> io::Result<()> { self.fsync() } pub fn truncate(&self, size: u64) -> io::Result<()> { cvt(syscall::ftruncate(self.0.raw(), size as usize))?; Ok(()) } pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) } pub fn write(&self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) } pub fn flush(&self) -> io::Result<()> { Ok(()) } pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> { let (whence, pos) = match pos { // Casting to `i64` is fine, too large values will end up as // negative which will cause an error in `lseek64`. SeekFrom::Start(off) => (syscall::SEEK_SET, off as i64), SeekFrom::End(off) => (syscall::SEEK_END, off), SeekFrom::Current(off) => (syscall::SEEK_CUR, off), }; let n = cvt(syscall::lseek(self.0.raw(), pos as isize, whence))?; Ok(n as u64) } pub fn duplicate(&self) -> io::Result<File> { self.0.duplicate().map(File) } pub fn dup(&self, buf: &[u8]) -> io::Result<File> { let fd = cvt(syscall::dup(*self.fd().as_inner() as usize, buf))?; Ok(File(FileDesc::new(fd))) } pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> { set_perm(&self.path()?, perm) } pub fn path(&self) -> io::Result<PathBuf> { let mut buf: [u8; 4096] = [0; 4096]; let count = cvt(syscall::fpath(*self.fd().as_inner() as usize, &mut buf))?; Ok(PathBuf::from(unsafe { String::from_utf8_unchecked(Vec::from(&buf[..count])) })) } pub fn fd(&self) -> &FileDesc { &self.0 } pub fn into_fd(self) -> FileDesc { self.0 } } impl DirBuilder { pub fn new() -> DirBuilder { DirBuilder { mode: 0o777 } } pub fn mkdir(&self, p: &Path) -> io::Result<()> { let flags = syscall::O_CREAT | syscall::O_CLOEXEC | syscall::O_DIRECTORY | syscall::O_EXCL; let fd = cvt(syscall::open(p.to_str().unwrap(), flags | (self.mode as usize & 0o777)))?; let _ = syscall::close(fd); Ok(()) } pub fn set_mode(&mut self, mode: u32) { self.mode = mode as u16; } } impl FromInner<usize> for File { fn from_inner(fd: usize) -> File { File(FileDesc::new(fd)) } } impl fmt::Debug for File { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut b = f.debug_struct("File"); b.field("fd", &self.0.raw()); if let Ok(path) = self.path() { b.field("path", &path); } /* if let Some((read, write)) = get_mode(fd) { b.field("read", &read).field("write", &write); } */ b.finish() } } pub fn readdir(p: &Path) -> io::Result<ReadDir> { let root = Arc::new(p.to_path_buf()); let flags = syscall::O_CLOEXEC | syscall::O_RDONLY | syscall::O_DIRECTORY; let fd = cvt(syscall::open(p.to_str().unwrap(), flags))?; let file = FileDesc::new(fd); let mut data = Vec::new(); file.read_to_end(&mut data)?; Ok(ReadDir { data: data, i: 0, root: root }) } pub fn unlink(p: &Path) -> io::Result<()> { cvt(syscall::unlink(p.to_str().unwrap()))?; Ok(()) } pub fn rename(old: &Path, new: &Path) -> io::Result<()> { let fd = cvt(syscall::open(old.to_str().unwrap(),
let res = cvt(syscall::frename(fd, new.to_str().unwrap())); cvt(syscall::close(fd))?; res?; Ok(()) } pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> { cvt(syscall::chmod(p.to_str().unwrap(), perm.mode as usize))?; Ok(()) } pub fn rmdir(p: &Path) -> io::Result<()> { cvt(syscall::rmdir(p.to_str().unwrap()))?; Ok(()) } pub fn remove_dir_all(path: &Path) -> io::Result<()> { let filetype = lstat(path)?.file_type(); if filetype.is_symlink() { unlink(path) } else { remove_dir_all_recursive(path) } } fn remove_dir_all_recursive(path: &Path) -> io::Result<()> { for child in readdir(path)? { let child = child?; if child.file_type()?.is_dir() { remove_dir_all_recursive(&child.path())?; } else { unlink(&child.path())?; } } rmdir(path) } pub fn readlink(p: &Path) -> io::Result<PathBuf> { let fd = cvt(syscall::open(p.to_str().unwrap(), syscall::O_CLOEXEC | syscall::O_SYMLINK | syscall::O_RDONLY))?; let mut buf: [u8; 4096] = [0; 4096]; let res = cvt(syscall::read(fd, &mut buf)); cvt(syscall::close(fd))?; let count = res?; Ok(PathBuf::from(unsafe { String::from_utf8_unchecked(Vec::from(&buf[..count])) })) } pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> { let fd = cvt(syscall::open(dst.to_str().unwrap(), syscall::O_CLOEXEC | syscall::O_SYMLINK | syscall::O_CREAT | syscall::O_WRONLY | 0o777))?; let res = cvt(syscall::write(fd, src.to_str().unwrap().as_bytes())); cvt(syscall::close(fd))?; res?; Ok(()) } pub fn link(_src: &Path, _dst: &Path) -> io::Result<()> { Err(Error::from_raw_os_error(syscall::ENOSYS)) } pub fn stat(p: &Path) -> io::Result<FileAttr> { let fd = cvt(syscall::open(p.to_str().unwrap(), syscall::O_CLOEXEC | syscall::O_STAT))?; let file = File(FileDesc::new(fd)); file.file_attr() } pub fn lstat(p: &Path) -> io::Result<FileAttr> { let fd = cvt(syscall::open(p.to_str().unwrap(), syscall::O_CLOEXEC | syscall::O_STAT | syscall::O_NOFOLLOW))?; let file = File(FileDesc::new(fd)); file.file_attr() } pub fn canonicalize(p: &Path) -> io::Result<PathBuf> { let fd = cvt(syscall::open(p.to_str().unwrap(), syscall::O_CLOEXEC | syscall::O_STAT))?; let file = File(FileDesc::new(fd)); file.path() } pub fn copy(from: &Path, to: &Path) -> io::Result<u64> { use fs::{File, set_permissions}; if !from.is_file() { return Err(Error::new(ErrorKind::InvalidInput, "the source path is not an existing regular file")) } let mut reader = File::open(from)?; let mut writer = File::create(to)?; let perm = reader.metadata()?.permissions(); let ret = io::copy(&mut reader, &mut writer)?; set_permissions(to, perm)?; Ok(ret) }
syscall::O_CLOEXEC | syscall::O_STAT | syscall::O_NOFOLLOW))?;
random_line_split
fs.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use os::unix::prelude::*; use ffi::{OsString, OsStr}; use fmt; use io::{self, Error, ErrorKind, SeekFrom}; use path::{Path, PathBuf}; use sync::Arc; use sys::fd::FileDesc; use sys::time::SystemTime; use sys::{cvt, syscall}; use sys_common::{AsInner, FromInner}; pub struct File(FileDesc); #[derive(Clone)] pub struct FileAttr { stat: syscall::Stat, } pub struct ReadDir { data: Vec<u8>, i: usize, root: Arc<PathBuf>, } struct Dir(FileDesc); unsafe impl Send for Dir {} unsafe impl Sync for Dir {} pub struct DirEntry { root: Arc<PathBuf>, name: Box<[u8]> } #[derive(Clone, Debug)] pub struct OpenOptions { // generic read: bool, write: bool, append: bool, truncate: bool, create: bool, create_new: bool, // system-specific custom_flags: i32, mode: u16, } #[derive(Clone, PartialEq, Eq, Debug)] pub struct FilePermissions { mode: u16 } #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] pub struct FileType { mode: u16 } #[derive(Debug)] pub struct DirBuilder { mode: u16 } impl FileAttr { pub fn size(&self) -> u64 { self.stat.st_size as u64 } pub fn perm(&self) -> FilePermissions { FilePermissions { mode: (self.stat.st_mode as u16) & 0o777 } } pub fn file_type(&self) -> FileType { FileType { mode: self.stat.st_mode as u16 } } } impl FileAttr { pub fn modified(&self) -> io::Result<SystemTime> { Ok(SystemTime::from(syscall::TimeSpec { tv_sec: self.stat.st_mtime as i64, tv_nsec: self.stat.st_mtime_nsec as i32, })) } pub fn accessed(&self) -> io::Result<SystemTime> { Ok(SystemTime::from(syscall::TimeSpec { tv_sec: self.stat.st_atime as i64, tv_nsec: self.stat.st_atime_nsec as i32, })) } pub fn created(&self) -> io::Result<SystemTime> { Ok(SystemTime::from(syscall::TimeSpec { tv_sec: self.stat.st_ctime as i64, tv_nsec: self.stat.st_ctime_nsec as i32, })) } } impl AsInner<syscall::Stat> for FileAttr { fn as_inner(&self) -> &syscall::Stat { &self.stat } } impl FilePermissions { pub fn readonly(&self) -> bool { self.mode & 0o222 == 0 } pub fn set_readonly(&mut self, readonly: bool) { if readonly { self.mode &= !0o222; } else { self.mode |= 0o222; } } pub fn mode(&self) -> u32 { self.mode as u32 } } impl FileType { pub fn is_dir(&self) -> bool { self.is(syscall::MODE_DIR) } pub fn is_file(&self) -> bool { self.is(syscall::MODE_FILE) } pub fn is_symlink(&self) -> bool { self.is(syscall::MODE_SYMLINK) } pub fn is(&self, mode: u16) -> bool { self.mode & syscall::MODE_TYPE == mode } } impl FromInner<u32> for FilePermissions { fn from_inner(mode: u32) -> FilePermissions { FilePermissions { mode: mode as u16 } } } impl fmt::Debug for ReadDir { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame. // Thus the result will be e g 'ReadDir("/home")' fmt::Debug::fmt(&*self.root, f) } } impl Iterator for ReadDir { type Item = io::Result<DirEntry>; fn next(&mut self) -> Option<io::Result<DirEntry>> { loop { let start = self.i; let mut i = self.i; while i < self.data.len() { self.i += 1; if self.data[i] == b'\n' { break; } i += 1; } if start < self.i { let ret = DirEntry { name: self.data[start .. i].to_owned().into_boxed_slice(), root: self.root.clone() }; if ret.name_bytes() != b"." && ret.name_bytes() != b".." { return Some(Ok(ret)) } } else { return None; } } } } impl DirEntry { pub fn path(&self) -> PathBuf { self.root.join(OsStr::from_bytes(self.name_bytes())) } pub fn file_name(&self) -> OsString { OsStr::from_bytes(self.name_bytes()).to_os_string() } pub fn metadata(&self) -> io::Result<FileAttr> { lstat(&self.path()) } pub fn file_type(&self) -> io::Result<FileType> { lstat(&self.path()).map(|m| m.file_type()) } fn name_bytes(&self) -> &[u8] { &*self.name } } impl OpenOptions { pub fn new() -> OpenOptions { OpenOptions { // generic read: false, write: false, append: false, truncate: false, create: false, create_new: false, // system-specific custom_flags: 0, mode: 0o666, } } pub fn read(&mut self, read: bool) { self.read = read; } pub fn write(&mut self, write: bool) { self.write = write; } pub fn append(&mut self, append: bool)
pub fn truncate(&mut self, truncate: bool) { self.truncate = truncate; } pub fn create(&mut self, create: bool) { self.create = create; } pub fn create_new(&mut self, create_new: bool) { self.create_new = create_new; } pub fn custom_flags(&mut self, flags: i32) { self.custom_flags = flags; } pub fn mode(&mut self, mode: u32) { self.mode = mode as u16; } fn get_access_mode(&self) -> io::Result<usize> { match (self.read, self.write, self.append) { (true, false, false) => Ok(syscall::O_RDONLY), (false, true, false) => Ok(syscall::O_WRONLY), (true, true, false) => Ok(syscall::O_RDWR), (false, _, true) => Ok(syscall::O_WRONLY | syscall::O_APPEND), (true, _, true) => Ok(syscall::O_RDWR | syscall::O_APPEND), (false, false, false) => Err(Error::from_raw_os_error(syscall::EINVAL)), } } fn get_creation_mode(&self) -> io::Result<usize> { match (self.write, self.append) { (true, false) => {} (false, false) => if self.truncate || self.create || self.create_new { return Err(Error::from_raw_os_error(syscall::EINVAL)); }, (_, true) => if self.truncate && !self.create_new { return Err(Error::from_raw_os_error(syscall::EINVAL)); }, } Ok(match (self.create, self.truncate, self.create_new) { (false, false, false) => 0, (true, false, false) => syscall::O_CREAT, (false, true, false) => syscall::O_TRUNC, (true, true, false) => syscall::O_CREAT | syscall::O_TRUNC, (_, _, true) => syscall::O_CREAT | syscall::O_EXCL, }) } } impl File { pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> { let flags = syscall::O_CLOEXEC | opts.get_access_mode()? as usize | opts.get_creation_mode()? as usize | (opts.custom_flags as usize & !syscall::O_ACCMODE); let fd = cvt(syscall::open(path.to_str().unwrap(), flags | opts.mode as usize))?; Ok(File(FileDesc::new(fd))) } pub fn file_attr(&self) -> io::Result<FileAttr> { let mut stat = syscall::Stat::default(); cvt(syscall::fstat(self.0.raw(), &mut stat))?; Ok(FileAttr { stat: stat }) } pub fn fsync(&self) -> io::Result<()> { cvt(syscall::fsync(self.0.raw()))?; Ok(()) } pub fn datasync(&self) -> io::Result<()> { self.fsync() } pub fn truncate(&self, size: u64) -> io::Result<()> { cvt(syscall::ftruncate(self.0.raw(), size as usize))?; Ok(()) } pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) } pub fn write(&self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) } pub fn flush(&self) -> io::Result<()> { Ok(()) } pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> { let (whence, pos) = match pos { // Casting to `i64` is fine, too large values will end up as // negative which will cause an error in `lseek64`. SeekFrom::Start(off) => (syscall::SEEK_SET, off as i64), SeekFrom::End(off) => (syscall::SEEK_END, off), SeekFrom::Current(off) => (syscall::SEEK_CUR, off), }; let n = cvt(syscall::lseek(self.0.raw(), pos as isize, whence))?; Ok(n as u64) } pub fn duplicate(&self) -> io::Result<File> { self.0.duplicate().map(File) } pub fn dup(&self, buf: &[u8]) -> io::Result<File> { let fd = cvt(syscall::dup(*self.fd().as_inner() as usize, buf))?; Ok(File(FileDesc::new(fd))) } pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> { set_perm(&self.path()?, perm) } pub fn path(&self) -> io::Result<PathBuf> { let mut buf: [u8; 4096] = [0; 4096]; let count = cvt(syscall::fpath(*self.fd().as_inner() as usize, &mut buf))?; Ok(PathBuf::from(unsafe { String::from_utf8_unchecked(Vec::from(&buf[..count])) })) } pub fn fd(&self) -> &FileDesc { &self.0 } pub fn into_fd(self) -> FileDesc { self.0 } } impl DirBuilder { pub fn new() -> DirBuilder { DirBuilder { mode: 0o777 } } pub fn mkdir(&self, p: &Path) -> io::Result<()> { let flags = syscall::O_CREAT | syscall::O_CLOEXEC | syscall::O_DIRECTORY | syscall::O_EXCL; let fd = cvt(syscall::open(p.to_str().unwrap(), flags | (self.mode as usize & 0o777)))?; let _ = syscall::close(fd); Ok(()) } pub fn set_mode(&mut self, mode: u32) { self.mode = mode as u16; } } impl FromInner<usize> for File { fn from_inner(fd: usize) -> File { File(FileDesc::new(fd)) } } impl fmt::Debug for File { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut b = f.debug_struct("File"); b.field("fd", &self.0.raw()); if let Ok(path) = self.path() { b.field("path", &path); } /* if let Some((read, write)) = get_mode(fd) { b.field("read", &read).field("write", &write); } */ b.finish() } } pub fn readdir(p: &Path) -> io::Result<ReadDir> { let root = Arc::new(p.to_path_buf()); let flags = syscall::O_CLOEXEC | syscall::O_RDONLY | syscall::O_DIRECTORY; let fd = cvt(syscall::open(p.to_str().unwrap(), flags))?; let file = FileDesc::new(fd); let mut data = Vec::new(); file.read_to_end(&mut data)?; Ok(ReadDir { data: data, i: 0, root: root }) } pub fn unlink(p: &Path) -> io::Result<()> { cvt(syscall::unlink(p.to_str().unwrap()))?; Ok(()) } pub fn rename(old: &Path, new: &Path) -> io::Result<()> { let fd = cvt(syscall::open(old.to_str().unwrap(), syscall::O_CLOEXEC | syscall::O_STAT | syscall::O_NOFOLLOW))?; let res = cvt(syscall::frename(fd, new.to_str().unwrap())); cvt(syscall::close(fd))?; res?; Ok(()) } pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> { cvt(syscall::chmod(p.to_str().unwrap(), perm.mode as usize))?; Ok(()) } pub fn rmdir(p: &Path) -> io::Result<()> { cvt(syscall::rmdir(p.to_str().unwrap()))?; Ok(()) } pub fn remove_dir_all(path: &Path) -> io::Result<()> { let filetype = lstat(path)?.file_type(); if filetype.is_symlink() { unlink(path) } else { remove_dir_all_recursive(path) } } fn remove_dir_all_recursive(path: &Path) -> io::Result<()> { for child in readdir(path)? { let child = child?; if child.file_type()?.is_dir() { remove_dir_all_recursive(&child.path())?; } else { unlink(&child.path())?; } } rmdir(path) } pub fn readlink(p: &Path) -> io::Result<PathBuf> { let fd = cvt(syscall::open(p.to_str().unwrap(), syscall::O_CLOEXEC | syscall::O_SYMLINK | syscall::O_RDONLY))?; let mut buf: [u8; 4096] = [0; 4096]; let res = cvt(syscall::read(fd, &mut buf)); cvt(syscall::close(fd))?; let count = res?; Ok(PathBuf::from(unsafe { String::from_utf8_unchecked(Vec::from(&buf[..count])) })) } pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> { let fd = cvt(syscall::open(dst.to_str().unwrap(), syscall::O_CLOEXEC | syscall::O_SYMLINK | syscall::O_CREAT | syscall::O_WRONLY | 0o777))?; let res = cvt(syscall::write(fd, src.to_str().unwrap().as_bytes())); cvt(syscall::close(fd))?; res?; Ok(()) } pub fn link(_src: &Path, _dst: &Path) -> io::Result<()> { Err(Error::from_raw_os_error(syscall::ENOSYS)) } pub fn stat(p: &Path) -> io::Result<FileAttr> { let fd = cvt(syscall::open(p.to_str().unwrap(), syscall::O_CLOEXEC | syscall::O_STAT))?; let file = File(FileDesc::new(fd)); file.file_attr() } pub fn lstat(p: &Path) -> io::Result<FileAttr> { let fd = cvt(syscall::open(p.to_str().unwrap(), syscall::O_CLOEXEC | syscall::O_STAT | syscall::O_NOFOLLOW))?; let file = File(FileDesc::new(fd)); file.file_attr() } pub fn canonicalize(p: &Path) -> io::Result<PathBuf> { let fd = cvt(syscall::open(p.to_str().unwrap(), syscall::O_CLOEXEC | syscall::O_STAT))?; let file = File(FileDesc::new(fd)); file.path() } pub fn copy(from: &Path, to: &Path) -> io::Result<u64> { use fs::{File, set_permissions}; if !from.is_file() { return Err(Error::new(ErrorKind::InvalidInput, "the source path is not an existing regular file")) } let mut reader = File::open(from)?; let mut writer = File::create(to)?; let perm = reader.metadata()?.permissions(); let ret = io::copy(&mut reader, &mut writer)?; set_permissions(to, perm)?; Ok(ret) }
{ self.append = append; }
identifier_body
fs.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use os::unix::prelude::*; use ffi::{OsString, OsStr}; use fmt; use io::{self, Error, ErrorKind, SeekFrom}; use path::{Path, PathBuf}; use sync::Arc; use sys::fd::FileDesc; use sys::time::SystemTime; use sys::{cvt, syscall}; use sys_common::{AsInner, FromInner}; pub struct File(FileDesc); #[derive(Clone)] pub struct FileAttr { stat: syscall::Stat, } pub struct ReadDir { data: Vec<u8>, i: usize, root: Arc<PathBuf>, } struct Dir(FileDesc); unsafe impl Send for Dir {} unsafe impl Sync for Dir {} pub struct DirEntry { root: Arc<PathBuf>, name: Box<[u8]> } #[derive(Clone, Debug)] pub struct OpenOptions { // generic read: bool, write: bool, append: bool, truncate: bool, create: bool, create_new: bool, // system-specific custom_flags: i32, mode: u16, } #[derive(Clone, PartialEq, Eq, Debug)] pub struct FilePermissions { mode: u16 } #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] pub struct FileType { mode: u16 } #[derive(Debug)] pub struct DirBuilder { mode: u16 } impl FileAttr { pub fn size(&self) -> u64 { self.stat.st_size as u64 } pub fn perm(&self) -> FilePermissions { FilePermissions { mode: (self.stat.st_mode as u16) & 0o777 } } pub fn file_type(&self) -> FileType { FileType { mode: self.stat.st_mode as u16 } } } impl FileAttr { pub fn modified(&self) -> io::Result<SystemTime> { Ok(SystemTime::from(syscall::TimeSpec { tv_sec: self.stat.st_mtime as i64, tv_nsec: self.stat.st_mtime_nsec as i32, })) } pub fn accessed(&self) -> io::Result<SystemTime> { Ok(SystemTime::from(syscall::TimeSpec { tv_sec: self.stat.st_atime as i64, tv_nsec: self.stat.st_atime_nsec as i32, })) } pub fn created(&self) -> io::Result<SystemTime> { Ok(SystemTime::from(syscall::TimeSpec { tv_sec: self.stat.st_ctime as i64, tv_nsec: self.stat.st_ctime_nsec as i32, })) } } impl AsInner<syscall::Stat> for FileAttr { fn as_inner(&self) -> &syscall::Stat { &self.stat } } impl FilePermissions { pub fn readonly(&self) -> bool { self.mode & 0o222 == 0 } pub fn set_readonly(&mut self, readonly: bool) { if readonly { self.mode &= !0o222; } else { self.mode |= 0o222; } } pub fn mode(&self) -> u32 { self.mode as u32 } } impl FileType { pub fn is_dir(&self) -> bool { self.is(syscall::MODE_DIR) } pub fn is_file(&self) -> bool { self.is(syscall::MODE_FILE) } pub fn is_symlink(&self) -> bool { self.is(syscall::MODE_SYMLINK) } pub fn is(&self, mode: u16) -> bool { self.mode & syscall::MODE_TYPE == mode } } impl FromInner<u32> for FilePermissions { fn from_inner(mode: u32) -> FilePermissions { FilePermissions { mode: mode as u16 } } } impl fmt::Debug for ReadDir { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame. // Thus the result will be e g 'ReadDir("/home")' fmt::Debug::fmt(&*self.root, f) } } impl Iterator for ReadDir { type Item = io::Result<DirEntry>; fn next(&mut self) -> Option<io::Result<DirEntry>> { loop { let start = self.i; let mut i = self.i; while i < self.data.len() { self.i += 1; if self.data[i] == b'\n' { break; } i += 1; } if start < self.i { let ret = DirEntry { name: self.data[start .. i].to_owned().into_boxed_slice(), root: self.root.clone() }; if ret.name_bytes() != b"." && ret.name_bytes() != b".." { return Some(Ok(ret)) } } else { return None; } } } } impl DirEntry { pub fn path(&self) -> PathBuf { self.root.join(OsStr::from_bytes(self.name_bytes())) } pub fn file_name(&self) -> OsString { OsStr::from_bytes(self.name_bytes()).to_os_string() } pub fn metadata(&self) -> io::Result<FileAttr> { lstat(&self.path()) } pub fn file_type(&self) -> io::Result<FileType> { lstat(&self.path()).map(|m| m.file_type()) } fn name_bytes(&self) -> &[u8] { &*self.name } } impl OpenOptions { pub fn new() -> OpenOptions { OpenOptions { // generic read: false, write: false, append: false, truncate: false, create: false, create_new: false, // system-specific custom_flags: 0, mode: 0o666, } } pub fn read(&mut self, read: bool) { self.read = read; } pub fn write(&mut self, write: bool) { self.write = write; } pub fn append(&mut self, append: bool) { self.append = append; } pub fn truncate(&mut self, truncate: bool) { self.truncate = truncate; } pub fn create(&mut self, create: bool) { self.create = create; } pub fn create_new(&mut self, create_new: bool) { self.create_new = create_new; } pub fn custom_flags(&mut self, flags: i32) { self.custom_flags = flags; } pub fn mode(&mut self, mode: u32) { self.mode = mode as u16; } fn get_access_mode(&self) -> io::Result<usize> { match (self.read, self.write, self.append) { (true, false, false) => Ok(syscall::O_RDONLY), (false, true, false) => Ok(syscall::O_WRONLY), (true, true, false) => Ok(syscall::O_RDWR), (false, _, true) => Ok(syscall::O_WRONLY | syscall::O_APPEND), (true, _, true) => Ok(syscall::O_RDWR | syscall::O_APPEND), (false, false, false) => Err(Error::from_raw_os_error(syscall::EINVAL)), } } fn get_creation_mode(&self) -> io::Result<usize> { match (self.write, self.append) { (true, false) => {} (false, false) => if self.truncate || self.create || self.create_new { return Err(Error::from_raw_os_error(syscall::EINVAL)); }, (_, true) => if self.truncate && !self.create_new { return Err(Error::from_raw_os_error(syscall::EINVAL)); }, } Ok(match (self.create, self.truncate, self.create_new) { (false, false, false) => 0, (true, false, false) => syscall::O_CREAT, (false, true, false) => syscall::O_TRUNC, (true, true, false) => syscall::O_CREAT | syscall::O_TRUNC, (_, _, true) => syscall::O_CREAT | syscall::O_EXCL, }) } } impl File { pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> { let flags = syscall::O_CLOEXEC | opts.get_access_mode()? as usize | opts.get_creation_mode()? as usize | (opts.custom_flags as usize & !syscall::O_ACCMODE); let fd = cvt(syscall::open(path.to_str().unwrap(), flags | opts.mode as usize))?; Ok(File(FileDesc::new(fd))) } pub fn file_attr(&self) -> io::Result<FileAttr> { let mut stat = syscall::Stat::default(); cvt(syscall::fstat(self.0.raw(), &mut stat))?; Ok(FileAttr { stat: stat }) } pub fn fsync(&self) -> io::Result<()> { cvt(syscall::fsync(self.0.raw()))?; Ok(()) } pub fn datasync(&self) -> io::Result<()> { self.fsync() } pub fn truncate(&self, size: u64) -> io::Result<()> { cvt(syscall::ftruncate(self.0.raw(), size as usize))?; Ok(()) } pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) } pub fn write(&self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) } pub fn flush(&self) -> io::Result<()> { Ok(()) } pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> { let (whence, pos) = match pos { // Casting to `i64` is fine, too large values will end up as // negative which will cause an error in `lseek64`. SeekFrom::Start(off) => (syscall::SEEK_SET, off as i64), SeekFrom::End(off) => (syscall::SEEK_END, off), SeekFrom::Current(off) => (syscall::SEEK_CUR, off), }; let n = cvt(syscall::lseek(self.0.raw(), pos as isize, whence))?; Ok(n as u64) } pub fn
(&self) -> io::Result<File> { self.0.duplicate().map(File) } pub fn dup(&self, buf: &[u8]) -> io::Result<File> { let fd = cvt(syscall::dup(*self.fd().as_inner() as usize, buf))?; Ok(File(FileDesc::new(fd))) } pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> { set_perm(&self.path()?, perm) } pub fn path(&self) -> io::Result<PathBuf> { let mut buf: [u8; 4096] = [0; 4096]; let count = cvt(syscall::fpath(*self.fd().as_inner() as usize, &mut buf))?; Ok(PathBuf::from(unsafe { String::from_utf8_unchecked(Vec::from(&buf[..count])) })) } pub fn fd(&self) -> &FileDesc { &self.0 } pub fn into_fd(self) -> FileDesc { self.0 } } impl DirBuilder { pub fn new() -> DirBuilder { DirBuilder { mode: 0o777 } } pub fn mkdir(&self, p: &Path) -> io::Result<()> { let flags = syscall::O_CREAT | syscall::O_CLOEXEC | syscall::O_DIRECTORY | syscall::O_EXCL; let fd = cvt(syscall::open(p.to_str().unwrap(), flags | (self.mode as usize & 0o777)))?; let _ = syscall::close(fd); Ok(()) } pub fn set_mode(&mut self, mode: u32) { self.mode = mode as u16; } } impl FromInner<usize> for File { fn from_inner(fd: usize) -> File { File(FileDesc::new(fd)) } } impl fmt::Debug for File { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut b = f.debug_struct("File"); b.field("fd", &self.0.raw()); if let Ok(path) = self.path() { b.field("path", &path); } /* if let Some((read, write)) = get_mode(fd) { b.field("read", &read).field("write", &write); } */ b.finish() } } pub fn readdir(p: &Path) -> io::Result<ReadDir> { let root = Arc::new(p.to_path_buf()); let flags = syscall::O_CLOEXEC | syscall::O_RDONLY | syscall::O_DIRECTORY; let fd = cvt(syscall::open(p.to_str().unwrap(), flags))?; let file = FileDesc::new(fd); let mut data = Vec::new(); file.read_to_end(&mut data)?; Ok(ReadDir { data: data, i: 0, root: root }) } pub fn unlink(p: &Path) -> io::Result<()> { cvt(syscall::unlink(p.to_str().unwrap()))?; Ok(()) } pub fn rename(old: &Path, new: &Path) -> io::Result<()> { let fd = cvt(syscall::open(old.to_str().unwrap(), syscall::O_CLOEXEC | syscall::O_STAT | syscall::O_NOFOLLOW))?; let res = cvt(syscall::frename(fd, new.to_str().unwrap())); cvt(syscall::close(fd))?; res?; Ok(()) } pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> { cvt(syscall::chmod(p.to_str().unwrap(), perm.mode as usize))?; Ok(()) } pub fn rmdir(p: &Path) -> io::Result<()> { cvt(syscall::rmdir(p.to_str().unwrap()))?; Ok(()) } pub fn remove_dir_all(path: &Path) -> io::Result<()> { let filetype = lstat(path)?.file_type(); if filetype.is_symlink() { unlink(path) } else { remove_dir_all_recursive(path) } } fn remove_dir_all_recursive(path: &Path) -> io::Result<()> { for child in readdir(path)? { let child = child?; if child.file_type()?.is_dir() { remove_dir_all_recursive(&child.path())?; } else { unlink(&child.path())?; } } rmdir(path) } pub fn readlink(p: &Path) -> io::Result<PathBuf> { let fd = cvt(syscall::open(p.to_str().unwrap(), syscall::O_CLOEXEC | syscall::O_SYMLINK | syscall::O_RDONLY))?; let mut buf: [u8; 4096] = [0; 4096]; let res = cvt(syscall::read(fd, &mut buf)); cvt(syscall::close(fd))?; let count = res?; Ok(PathBuf::from(unsafe { String::from_utf8_unchecked(Vec::from(&buf[..count])) })) } pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> { let fd = cvt(syscall::open(dst.to_str().unwrap(), syscall::O_CLOEXEC | syscall::O_SYMLINK | syscall::O_CREAT | syscall::O_WRONLY | 0o777))?; let res = cvt(syscall::write(fd, src.to_str().unwrap().as_bytes())); cvt(syscall::close(fd))?; res?; Ok(()) } pub fn link(_src: &Path, _dst: &Path) -> io::Result<()> { Err(Error::from_raw_os_error(syscall::ENOSYS)) } pub fn stat(p: &Path) -> io::Result<FileAttr> { let fd = cvt(syscall::open(p.to_str().unwrap(), syscall::O_CLOEXEC | syscall::O_STAT))?; let file = File(FileDesc::new(fd)); file.file_attr() } pub fn lstat(p: &Path) -> io::Result<FileAttr> { let fd = cvt(syscall::open(p.to_str().unwrap(), syscall::O_CLOEXEC | syscall::O_STAT | syscall::O_NOFOLLOW))?; let file = File(FileDesc::new(fd)); file.file_attr() } pub fn canonicalize(p: &Path) -> io::Result<PathBuf> { let fd = cvt(syscall::open(p.to_str().unwrap(), syscall::O_CLOEXEC | syscall::O_STAT))?; let file = File(FileDesc::new(fd)); file.path() } pub fn copy(from: &Path, to: &Path) -> io::Result<u64> { use fs::{File, set_permissions}; if !from.is_file() { return Err(Error::new(ErrorKind::InvalidInput, "the source path is not an existing regular file")) } let mut reader = File::open(from)?; let mut writer = File::create(to)?; let perm = reader.metadata()?.permissions(); let ret = io::copy(&mut reader, &mut writer)?; set_permissions(to, perm)?; Ok(ret) }
duplicate
identifier_name
event_event.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields, api, _ from odoo.addons.http_routing.models.ir_http import slug class EventEvent(models.Model): _inherit = "event.event" community_menu = fields.Boolean( "Community Menu", compute="_compute_community_menu", readonly=False, store=True, help="Display community tab on website") community_menu_ids = fields.One2many( "website.event.menu", "event_id", string="Event Community Menus", domain=[("menu_type", "=", "community")]) @api.depends("event_type_id", "website_menu", "community_menu") def _compute_community_menu(self): """ At type onchange: synchronize. At website_menu update: synchronize. """ for event in self: if event.event_type_id and event.event_type_id != event._origin.event_type_id: event.community_menu = event.event_type_id.community_menu elif event.website_menu and event.website_menu != event._origin.website_menu or not event.community_menu: event.community_menu = True elif not event.website_menu: event.community_menu = False # ------------------------------------------------------------ # WEBSITE MENU MANAGEMENT # ------------------------------------------------------------ # OVERRIDES: ADD SEQUENCE def _get_menu_update_fields(self): update_fields = super(EventEvent, self)._get_menu_update_fields() update_fields += ['community_menu'] return update_fields def _update_website_menus(self, menus_update_by_field=None): super(EventEvent, self)._update_website_menus(menus_update_by_field=menus_update_by_field) for event in self: if event.menu_id and (not menus_update_by_field or event in menus_update_by_field.get('community_menu')): event._update_website_menu_entry('community_menu', 'community_menu_ids', '_get_community_menu_entries') def _get_menu_type_field_matching(self): res = super(EventEvent, self)._get_menu_type_field_matching() res['community'] = 'community_menu' return res def _get_community_menu_entries(self): self.ensure_one() return [(_('Community'), '/event/%s/community' % slug(self), False, 80, 'community')] def _get_track_menu_entries(self): """ Remove agenda as this is now managed separately """ self.ensure_one() return [ (_('Talks'), '/event/%s/track' % slug(self), False, 10, 'track'), (_('Agenda'), '/event/%s/agenda' % slug(self), False, 70, 'track') ] def
(self): """ See website_event_track._get_track_menu_entries() """ self.ensure_one() return [(_('Talk Proposals'), '/event/%s/track_proposal' % slug(self), False, 15, 'track_proposal')]
_get_track_proposal_menu_entries
identifier_name
event_event.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields, api, _ from odoo.addons.http_routing.models.ir_http import slug class EventEvent(models.Model): _inherit = "event.event" community_menu = fields.Boolean( "Community Menu", compute="_compute_community_menu", readonly=False, store=True, help="Display community tab on website") community_menu_ids = fields.One2many( "website.event.menu", "event_id", string="Event Community Menus", domain=[("menu_type", "=", "community")]) @api.depends("event_type_id", "website_menu", "community_menu") def _compute_community_menu(self): """ At type onchange: synchronize. At website_menu update: synchronize. """ for event in self: if event.event_type_id and event.event_type_id != event._origin.event_type_id: event.community_menu = event.event_type_id.community_menu elif event.website_menu and event.website_menu != event._origin.website_menu or not event.community_menu: event.community_menu = True elif not event.website_menu: event.community_menu = False # ------------------------------------------------------------ # WEBSITE MENU MANAGEMENT # ------------------------------------------------------------ # OVERRIDES: ADD SEQUENCE def _get_menu_update_fields(self): update_fields = super(EventEvent, self)._get_menu_update_fields() update_fields += ['community_menu'] return update_fields def _update_website_menus(self, menus_update_by_field=None): super(EventEvent, self)._update_website_menus(menus_update_by_field=menus_update_by_field) for event in self: if event.menu_id and (not menus_update_by_field or event in menus_update_by_field.get('community_menu')): event._update_website_menu_entry('community_menu', 'community_menu_ids', '_get_community_menu_entries') def _get_menu_type_field_matching(self):
def _get_community_menu_entries(self): self.ensure_one() return [(_('Community'), '/event/%s/community' % slug(self), False, 80, 'community')] def _get_track_menu_entries(self): """ Remove agenda as this is now managed separately """ self.ensure_one() return [ (_('Talks'), '/event/%s/track' % slug(self), False, 10, 'track'), (_('Agenda'), '/event/%s/agenda' % slug(self), False, 70, 'track') ] def _get_track_proposal_menu_entries(self): """ See website_event_track._get_track_menu_entries() """ self.ensure_one() return [(_('Talk Proposals'), '/event/%s/track_proposal' % slug(self), False, 15, 'track_proposal')]
res = super(EventEvent, self)._get_menu_type_field_matching() res['community'] = 'community_menu' return res
random_line_split
event_event.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields, api, _ from odoo.addons.http_routing.models.ir_http import slug class EventEvent(models.Model): _inherit = "event.event" community_menu = fields.Boolean( "Community Menu", compute="_compute_community_menu", readonly=False, store=True, help="Display community tab on website") community_menu_ids = fields.One2many( "website.event.menu", "event_id", string="Event Community Menus", domain=[("menu_type", "=", "community")]) @api.depends("event_type_id", "website_menu", "community_menu") def _compute_community_menu(self): """ At type onchange: synchronize. At website_menu update: synchronize. """ for event in self:
# ------------------------------------------------------------ # WEBSITE MENU MANAGEMENT # ------------------------------------------------------------ # OVERRIDES: ADD SEQUENCE def _get_menu_update_fields(self): update_fields = super(EventEvent, self)._get_menu_update_fields() update_fields += ['community_menu'] return update_fields def _update_website_menus(self, menus_update_by_field=None): super(EventEvent, self)._update_website_menus(menus_update_by_field=menus_update_by_field) for event in self: if event.menu_id and (not menus_update_by_field or event in menus_update_by_field.get('community_menu')): event._update_website_menu_entry('community_menu', 'community_menu_ids', '_get_community_menu_entries') def _get_menu_type_field_matching(self): res = super(EventEvent, self)._get_menu_type_field_matching() res['community'] = 'community_menu' return res def _get_community_menu_entries(self): self.ensure_one() return [(_('Community'), '/event/%s/community' % slug(self), False, 80, 'community')] def _get_track_menu_entries(self): """ Remove agenda as this is now managed separately """ self.ensure_one() return [ (_('Talks'), '/event/%s/track' % slug(self), False, 10, 'track'), (_('Agenda'), '/event/%s/agenda' % slug(self), False, 70, 'track') ] def _get_track_proposal_menu_entries(self): """ See website_event_track._get_track_menu_entries() """ self.ensure_one() return [(_('Talk Proposals'), '/event/%s/track_proposal' % slug(self), False, 15, 'track_proposal')]
if event.event_type_id and event.event_type_id != event._origin.event_type_id: event.community_menu = event.event_type_id.community_menu elif event.website_menu and event.website_menu != event._origin.website_menu or not event.community_menu: event.community_menu = True elif not event.website_menu: event.community_menu = False
conditional_block
event_event.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields, api, _ from odoo.addons.http_routing.models.ir_http import slug class EventEvent(models.Model): _inherit = "event.event" community_menu = fields.Boolean( "Community Menu", compute="_compute_community_menu", readonly=False, store=True, help="Display community tab on website") community_menu_ids = fields.One2many( "website.event.menu", "event_id", string="Event Community Menus", domain=[("menu_type", "=", "community")]) @api.depends("event_type_id", "website_menu", "community_menu") def _compute_community_menu(self): """ At type onchange: synchronize. At website_menu update: synchronize. """ for event in self: if event.event_type_id and event.event_type_id != event._origin.event_type_id: event.community_menu = event.event_type_id.community_menu elif event.website_menu and event.website_menu != event._origin.website_menu or not event.community_menu: event.community_menu = True elif not event.website_menu: event.community_menu = False # ------------------------------------------------------------ # WEBSITE MENU MANAGEMENT # ------------------------------------------------------------ # OVERRIDES: ADD SEQUENCE def _get_menu_update_fields(self): update_fields = super(EventEvent, self)._get_menu_update_fields() update_fields += ['community_menu'] return update_fields def _update_website_menus(self, menus_update_by_field=None): super(EventEvent, self)._update_website_menus(menus_update_by_field=menus_update_by_field) for event in self: if event.menu_id and (not menus_update_by_field or event in menus_update_by_field.get('community_menu')): event._update_website_menu_entry('community_menu', 'community_menu_ids', '_get_community_menu_entries') def _get_menu_type_field_matching(self):
def _get_community_menu_entries(self): self.ensure_one() return [(_('Community'), '/event/%s/community' % slug(self), False, 80, 'community')] def _get_track_menu_entries(self): """ Remove agenda as this is now managed separately """ self.ensure_one() return [ (_('Talks'), '/event/%s/track' % slug(self), False, 10, 'track'), (_('Agenda'), '/event/%s/agenda' % slug(self), False, 70, 'track') ] def _get_track_proposal_menu_entries(self): """ See website_event_track._get_track_menu_entries() """ self.ensure_one() return [(_('Talk Proposals'), '/event/%s/track_proposal' % slug(self), False, 15, 'track_proposal')]
res = super(EventEvent, self)._get_menu_type_field_matching() res['community'] = 'community_menu' return res
identifier_body
login.component.ts
import { FormBuilder } from '@angular/forms'; import { Http } from '@angular/http'; import { FormGroup } from '@angular/forms'; import { Component, OnInit } from '@angular/core'; import { SecurityService } from 'app/security.service'; @Component({ selector: 'cf-login', template: ` <form [formGroup]="loginForm" class="container"> <section name="email-control"> <label for="email">Email:</label> <input formControlName="email" type="email" /> <small *ngIf="loginForm.get('email').invalid" class="float-right"> email is required </small> </section> <section name="password-control"> <label for="password">Password:</label> <input formControlName="password" type="password" /> <small *ngIf="loginForm.get('password').invalid" class="float-right"> password is required </small> </section> <button (click)="onRegister()" [disabled]="loginForm.invalid">Register</button> <button (click)="onLogIn()" [disabled]="loginForm.invalid">Log In</button> </form> `, styles: [] }) export class LoginComponent implements OnInit { public loginForm: FormGroup constructor(public security: SecurityService, public formBuilder: FormBuilder)
ngOnInit() { this.loginForm = this.formBuilder.group({ email: '', password: '' }); } onRegister() { const credentials = this.loginForm.value; this.security .registerUser(credentials) } onLogIn() { const credentials = this.loginForm.value; this.security .logInUser(credentials) } }
{ }
identifier_body
login.component.ts
import { FormBuilder } from '@angular/forms'; import { Http } from '@angular/http'; import { FormGroup } from '@angular/forms'; import { Component, OnInit } from '@angular/core'; import { SecurityService } from 'app/security.service'; @Component({ selector: 'cf-login', template: ` <form [formGroup]="loginForm" class="container"> <section name="email-control"> <label for="email">Email:</label> <input formControlName="email" type="email" /> <small *ngIf="loginForm.get('email').invalid" class="float-right"> email is required </small> </section> <section name="password-control"> <label for="password">Password:</label> <input formControlName="password" type="password" /> <small *ngIf="loginForm.get('password').invalid" class="float-right"> password is required </small> </section> <button (click)="onRegister()" [disabled]="loginForm.invalid">Register</button> <button (click)="onLogIn()" [disabled]="loginForm.invalid">Log In</button> </form> `, styles: [] }) export class LoginComponent implements OnInit { public loginForm: FormGroup constructor(public security: SecurityService, public formBuilder: FormBuilder) { }
() { this.loginForm = this.formBuilder.group({ email: '', password: '' }); } onRegister() { const credentials = this.loginForm.value; this.security .registerUser(credentials) } onLogIn() { const credentials = this.loginForm.value; this.security .logInUser(credentials) } }
ngOnInit
identifier_name
login.component.ts
import { FormBuilder } from '@angular/forms'; import { Http } from '@angular/http'; import { FormGroup } from '@angular/forms'; import { Component, OnInit } from '@angular/core'; import { SecurityService } from 'app/security.service'; @Component({ selector: 'cf-login', template: ` <form [formGroup]="loginForm" class="container"> <section name="email-control"> <label for="email">Email:</label> <input formControlName="email" type="email" /> <small *ngIf="loginForm.get('email').invalid" class="float-right"> email is required </small> </section> <section name="password-control"> <label for="password">Password:</label> <input formControlName="password" type="password" /> <small *ngIf="loginForm.get('password').invalid" class="float-right"> password is required </small> </section>
</form> `, styles: [] }) export class LoginComponent implements OnInit { public loginForm: FormGroup constructor(public security: SecurityService, public formBuilder: FormBuilder) { } ngOnInit() { this.loginForm = this.formBuilder.group({ email: '', password: '' }); } onRegister() { const credentials = this.loginForm.value; this.security .registerUser(credentials) } onLogIn() { const credentials = this.loginForm.value; this.security .logInUser(credentials) } }
<button (click)="onRegister()" [disabled]="loginForm.invalid">Register</button> <button (click)="onLogIn()" [disabled]="loginForm.invalid">Log In</button>
random_line_split
mkfifo.rs
#![crate_name = "uu_mkfifo"] /* * This file is part of the uutils coreutils package. * * (c) Michael Gehring <mg@ebfe.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; extern crate libc; #[macro_use] extern crate uucore; use libc::mkfifo; use std::ffi::CString; use std::io::{Error, Write}; static NAME: &'static str = "mkfifo"; static VERSION: &'static str = env!("CARGO_PKG_VERSION"); pub fn
(args: Vec<String>) -> i32 { let mut opts = getopts::Options::new(); opts.optopt("m", "mode", "file permissions for the fifo", "(default 0666)"); opts.optflag("h", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(err) => panic!("{}", err), }; if matches.opt_present("version") { println!("{} {}", NAME, VERSION); return 0; } if matches.opt_present("help") || matches.free.is_empty() { let msg = format!("{0} {1} Usage: {0} [OPTIONS] NAME... Create a FIFO with the given name.", NAME, VERSION); print!("{}", opts.usage(&msg)); if matches.free.is_empty() { return 1; } return 0; } let mode = match matches.opt_str("m") { Some(m) => match usize::from_str_radix(&m, 8) { Ok(m) => m, Err(e)=> { show_error!("invalid mode: {}", e); return 1; } }, None => 0o666, }; let mut exit_status = 0; for f in &matches.free { let err = unsafe { mkfifo(CString::new(f.as_bytes()).unwrap().as_ptr(), mode as libc::mode_t) }; if err == -1 { show_error!("creating '{}': {}", f, Error::last_os_error().raw_os_error().unwrap()); exit_status = 1; } } exit_status }
uumain
identifier_name
mkfifo.rs
#![crate_name = "uu_mkfifo"] /* * This file is part of the uutils coreutils package. * * (c) Michael Gehring <mg@ebfe.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; extern crate libc; #[macro_use] extern crate uucore; use libc::mkfifo; use std::ffi::CString; use std::io::{Error, Write}; static NAME: &'static str = "mkfifo"; static VERSION: &'static str = env!("CARGO_PKG_VERSION"); pub fn uumain(args: Vec<String>) -> i32
{ let mut opts = getopts::Options::new(); opts.optopt("m", "mode", "file permissions for the fifo", "(default 0666)"); opts.optflag("h", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(err) => panic!("{}", err), }; if matches.opt_present("version") { println!("{} {}", NAME, VERSION); return 0; } if matches.opt_present("help") || matches.free.is_empty() { let msg = format!("{0} {1} Usage: {0} [OPTIONS] NAME... Create a FIFO with the given name.", NAME, VERSION); print!("{}", opts.usage(&msg)); if matches.free.is_empty() { return 1; } return 0; } let mode = match matches.opt_str("m") { Some(m) => match usize::from_str_radix(&m, 8) { Ok(m) => m, Err(e)=> { show_error!("invalid mode: {}", e); return 1; } }, None => 0o666, }; let mut exit_status = 0; for f in &matches.free { let err = unsafe { mkfifo(CString::new(f.as_bytes()).unwrap().as_ptr(), mode as libc::mode_t) }; if err == -1 { show_error!("creating '{}': {}", f, Error::last_os_error().raw_os_error().unwrap()); exit_status = 1; } } exit_status }
identifier_body
mkfifo.rs
#![crate_name = "uu_mkfifo"] /* * This file is part of the uutils coreutils package. * * (c) Michael Gehring <mg@ebfe.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; extern crate libc; #[macro_use] extern crate uucore; use libc::mkfifo; use std::ffi::CString; use std::io::{Error, Write}; static NAME: &'static str = "mkfifo"; static VERSION: &'static str = env!("CARGO_PKG_VERSION"); pub fn uumain(args: Vec<String>) -> i32 { let mut opts = getopts::Options::new(); opts.optopt("m", "mode", "file permissions for the fifo", "(default 0666)"); opts.optflag("h", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(err) => panic!("{}", err), }; if matches.opt_present("version") { println!("{} {}", NAME, VERSION); return 0; } if matches.opt_present("help") || matches.free.is_empty()
let mode = match matches.opt_str("m") { Some(m) => match usize::from_str_radix(&m, 8) { Ok(m) => m, Err(e)=> { show_error!("invalid mode: {}", e); return 1; } }, None => 0o666, }; let mut exit_status = 0; for f in &matches.free { let err = unsafe { mkfifo(CString::new(f.as_bytes()).unwrap().as_ptr(), mode as libc::mode_t) }; if err == -1 { show_error!("creating '{}': {}", f, Error::last_os_error().raw_os_error().unwrap()); exit_status = 1; } } exit_status }
{ let msg = format!("{0} {1} Usage: {0} [OPTIONS] NAME... Create a FIFO with the given name.", NAME, VERSION); print!("{}", opts.usage(&msg)); if matches.free.is_empty() { return 1; } return 0; }
conditional_block
terraindisplay.py
"""Module for displaying Terrain, both in 2D and 3D. (Not accessible outside of package; use display methods of Terrain instead.) """ from Tkinter import Tk, Canvas, Frame, BOTH from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np class Terrain2D(Frame): """2D graphical representation of a Terrain object. Consists of a 2D top-down image of terrain as a grid of greyscale squares. Each square corresponds to a height value, being on a scale from white if 1 to black if 0. """ SQUARE_SIDE = 3 """Length of one side of colored square.""" @classmethod def
(cls, terrain): """Display a Terrain in 2D. Args: terrain (Terrain): Terrain to display. """ root = Tk() dimensions = "{0}x{1}".format(terrain.width * Terrain2D.SQUARE_SIDE, terrain.length * Terrain2D.SQUARE_SIDE) root.geometry(dimensions) app = Terrain2D(root, terrain) root.mainloop() def __init__(self, parent, terrain): """Make self child of a TK parent, then initialize own UI. Args: parent (TK): Parent to attach self to. terrain (Terrain): Terrain to display. """ Frame.__init__(self, parent) self.terrain = terrain self.parent = parent self.init_ui() def init_ui(self): """Initialize UI of window.""" self.parent.title("Terrain (top-down)") self.pack(fill=BOTH, expand=1) self.draw_heights() def draw_heights(self): """Draw grid of height values on window. Heights are shown as squares, with greyscale colors becoming brighter for greater heights. """ canvas = Canvas(self) for x in range(self.terrain.width): for y in range(self.terrain.length): x_pos = x * Terrain2D.SQUARE_SIDE y_pos = y * Terrain2D.SQUARE_SIDE color = int(self.terrain[x, y] * 15) hex_color = "#" + "0123456789abcdef"[color] * 3 canvas.create_rectangle(x_pos, y_pos, x_pos + Terrain2D.SQUARE_SIDE, y_pos + Terrain2D.SQUARE_SIDE, outline=hex_color, fill=hex_color) canvas.pack(fill=BOTH, expand=1) class Terrain3D(object): """A 3D representation of a Terrain. Consists of a 3D surface mesh, shown at an angle. Can be seen at different angles. Uses matplotlib.mplot3d to display rudimentary 3D version of terrain. Notes: Is somewhat guaranteed to be slow. Not intended for use other than visualizing terrain during development. """ def __init__(self, terrain): self.terrain = terrain self.x_grid, self.y_grid = np.meshgrid(range(self.terrain.width), range(self.terrain.length)) z_vals = np.array([self.terrain[x, y] for x, y in zip(np.ravel(self.x_grid), np.ravel(self.y_grid))]) self.z_grid = z_vals.reshape(self.x_grid.shape) def display_terrain(self): """Display 3D surface of terrain.""" fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.plot_surface(self.x_grid, self.y_grid, self.z_grid) ax.set_zlim(0.0, 1.0) plt.show()
display_terrain
identifier_name
terraindisplay.py
"""Module for displaying Terrain, both in 2D and 3D. (Not accessible outside of package; use display methods of Terrain instead.) """ from Tkinter import Tk, Canvas, Frame, BOTH from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np class Terrain2D(Frame): """2D graphical representation of a Terrain object. Consists of a 2D top-down image of terrain as a grid of greyscale squares. Each square corresponds to a height value, being on a scale from white if 1 to black if 0. """ SQUARE_SIDE = 3 """Length of one side of colored square.""" @classmethod def display_terrain(cls, terrain): """Display a Terrain in 2D. Args: terrain (Terrain): Terrain to display. """ root = Tk() dimensions = "{0}x{1}".format(terrain.width * Terrain2D.SQUARE_SIDE, terrain.length * Terrain2D.SQUARE_SIDE) root.geometry(dimensions) app = Terrain2D(root, terrain) root.mainloop() def __init__(self, parent, terrain): """Make self child of a TK parent, then initialize own UI. Args: parent (TK): Parent to attach self to. terrain (Terrain): Terrain to display. """ Frame.__init__(self, parent) self.terrain = terrain self.parent = parent self.init_ui() def init_ui(self): """Initialize UI of window.""" self.parent.title("Terrain (top-down)") self.pack(fill=BOTH, expand=1) self.draw_heights() def draw_heights(self): """Draw grid of height values on window. Heights are shown as squares, with greyscale colors becoming brighter for greater heights. """ canvas = Canvas(self) for x in range(self.terrain.width): for y in range(self.terrain.length): x_pos = x * Terrain2D.SQUARE_SIDE y_pos = y * Terrain2D.SQUARE_SIDE color = int(self.terrain[x, y] * 15) hex_color = "#" + "0123456789abcdef"[color] * 3 canvas.create_rectangle(x_pos, y_pos, x_pos + Terrain2D.SQUARE_SIDE, y_pos + Terrain2D.SQUARE_SIDE, outline=hex_color, fill=hex_color) canvas.pack(fill=BOTH, expand=1) class Terrain3D(object): """A 3D representation of a Terrain. Consists of a 3D surface mesh, shown at an angle. Can be seen at different angles. Uses matplotlib.mplot3d to display rudimentary 3D version of terrain. Notes: Is somewhat guaranteed to be slow. Not intended for use other than visualizing terrain during development. """
def __init__(self, terrain): self.terrain = terrain self.x_grid, self.y_grid = np.meshgrid(range(self.terrain.width), range(self.terrain.length)) z_vals = np.array([self.terrain[x, y] for x, y in zip(np.ravel(self.x_grid), np.ravel(self.y_grid))]) self.z_grid = z_vals.reshape(self.x_grid.shape) def display_terrain(self): """Display 3D surface of terrain.""" fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.plot_surface(self.x_grid, self.y_grid, self.z_grid) ax.set_zlim(0.0, 1.0) plt.show()
random_line_split
terraindisplay.py
"""Module for displaying Terrain, both in 2D and 3D. (Not accessible outside of package; use display methods of Terrain instead.) """ from Tkinter import Tk, Canvas, Frame, BOTH from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np class Terrain2D(Frame): """2D graphical representation of a Terrain object. Consists of a 2D top-down image of terrain as a grid of greyscale squares. Each square corresponds to a height value, being on a scale from white if 1 to black if 0. """ SQUARE_SIDE = 3 """Length of one side of colored square.""" @classmethod def display_terrain(cls, terrain): """Display a Terrain in 2D. Args: terrain (Terrain): Terrain to display. """ root = Tk() dimensions = "{0}x{1}".format(terrain.width * Terrain2D.SQUARE_SIDE, terrain.length * Terrain2D.SQUARE_SIDE) root.geometry(dimensions) app = Terrain2D(root, terrain) root.mainloop() def __init__(self, parent, terrain): """Make self child of a TK parent, then initialize own UI. Args: parent (TK): Parent to attach self to. terrain (Terrain): Terrain to display. """ Frame.__init__(self, parent) self.terrain = terrain self.parent = parent self.init_ui() def init_ui(self): """Initialize UI of window.""" self.parent.title("Terrain (top-down)") self.pack(fill=BOTH, expand=1) self.draw_heights() def draw_heights(self): """Draw grid of height values on window. Heights are shown as squares, with greyscale colors becoming brighter for greater heights. """ canvas = Canvas(self) for x in range(self.terrain.width): for y in range(self.terrain.length): x_pos = x * Terrain2D.SQUARE_SIDE y_pos = y * Terrain2D.SQUARE_SIDE color = int(self.terrain[x, y] * 15) hex_color = "#" + "0123456789abcdef"[color] * 3 canvas.create_rectangle(x_pos, y_pos, x_pos + Terrain2D.SQUARE_SIDE, y_pos + Terrain2D.SQUARE_SIDE, outline=hex_color, fill=hex_color) canvas.pack(fill=BOTH, expand=1) class Terrain3D(object): """A 3D representation of a Terrain. Consists of a 3D surface mesh, shown at an angle. Can be seen at different angles. Uses matplotlib.mplot3d to display rudimentary 3D version of terrain. Notes: Is somewhat guaranteed to be slow. Not intended for use other than visualizing terrain during development. """ def __init__(self, terrain):
def display_terrain(self): """Display 3D surface of terrain.""" fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.plot_surface(self.x_grid, self.y_grid, self.z_grid) ax.set_zlim(0.0, 1.0) plt.show()
self.terrain = terrain self.x_grid, self.y_grid = np.meshgrid(range(self.terrain.width), range(self.terrain.length)) z_vals = np.array([self.terrain[x, y] for x, y in zip(np.ravel(self.x_grid), np.ravel(self.y_grid))]) self.z_grid = z_vals.reshape(self.x_grid.shape)
identifier_body
terraindisplay.py
"""Module for displaying Terrain, both in 2D and 3D. (Not accessible outside of package; use display methods of Terrain instead.) """ from Tkinter import Tk, Canvas, Frame, BOTH from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np class Terrain2D(Frame): """2D graphical representation of a Terrain object. Consists of a 2D top-down image of terrain as a grid of greyscale squares. Each square corresponds to a height value, being on a scale from white if 1 to black if 0. """ SQUARE_SIDE = 3 """Length of one side of colored square.""" @classmethod def display_terrain(cls, terrain): """Display a Terrain in 2D. Args: terrain (Terrain): Terrain to display. """ root = Tk() dimensions = "{0}x{1}".format(terrain.width * Terrain2D.SQUARE_SIDE, terrain.length * Terrain2D.SQUARE_SIDE) root.geometry(dimensions) app = Terrain2D(root, terrain) root.mainloop() def __init__(self, parent, terrain): """Make self child of a TK parent, then initialize own UI. Args: parent (TK): Parent to attach self to. terrain (Terrain): Terrain to display. """ Frame.__init__(self, parent) self.terrain = terrain self.parent = parent self.init_ui() def init_ui(self): """Initialize UI of window.""" self.parent.title("Terrain (top-down)") self.pack(fill=BOTH, expand=1) self.draw_heights() def draw_heights(self): """Draw grid of height values on window. Heights are shown as squares, with greyscale colors becoming brighter for greater heights. """ canvas = Canvas(self) for x in range(self.terrain.width): for y in range(self.terrain.length):
canvas.pack(fill=BOTH, expand=1) class Terrain3D(object): """A 3D representation of a Terrain. Consists of a 3D surface mesh, shown at an angle. Can be seen at different angles. Uses matplotlib.mplot3d to display rudimentary 3D version of terrain. Notes: Is somewhat guaranteed to be slow. Not intended for use other than visualizing terrain during development. """ def __init__(self, terrain): self.terrain = terrain self.x_grid, self.y_grid = np.meshgrid(range(self.terrain.width), range(self.terrain.length)) z_vals = np.array([self.terrain[x, y] for x, y in zip(np.ravel(self.x_grid), np.ravel(self.y_grid))]) self.z_grid = z_vals.reshape(self.x_grid.shape) def display_terrain(self): """Display 3D surface of terrain.""" fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.plot_surface(self.x_grid, self.y_grid, self.z_grid) ax.set_zlim(0.0, 1.0) plt.show()
x_pos = x * Terrain2D.SQUARE_SIDE y_pos = y * Terrain2D.SQUARE_SIDE color = int(self.terrain[x, y] * 15) hex_color = "#" + "0123456789abcdef"[color] * 3 canvas.create_rectangle(x_pos, y_pos, x_pos + Terrain2D.SQUARE_SIDE, y_pos + Terrain2D.SQUARE_SIDE, outline=hex_color, fill=hex_color)
conditional_block
binnode.rs
use std::collections::Bitv; use BinGraph; /// Contains a binary state and the choices. #[deriving(PartialEq, Eq, Show, Clone)] pub struct BinNode { /// The state composed of bits. pub state: Bitv, /// The choices represented as bits that can be flipped. pub choices: Bitv } impl BinNode { /// Gets pairs from pair of booleans. pub fn from_pairs(pairs: &[(bool, bool)]) -> BinNode { BinNode { state: pairs.iter().map(|&(a, _)| a).collect(), choices: pairs.iter().map(|&(_, b)| b).collect() } } /// Call closure for each available choice. #[inline(always)] pub fn with_choices(&self, f: |i: uint|) { for i in range(0, self.choices.len()) .zip(self.choices.iter()) .filter(|&(_, v)| v) .map(|(i, _)| i ) { f(i) } } /// Calls closure for all choices that are not in graph. #[inline(always)] pub fn with_choices_not_in<TAction>( &self, graph: &BinGraph<TAction>, f: |i: uint| ) { self.with_choices(|i| if !graph.contains_choice(self, i)
) } }
{ f(i) }
conditional_block
binnode.rs
use std::collections::Bitv; use BinGraph; /// Contains a binary state and the choices. #[deriving(PartialEq, Eq, Show, Clone)] pub struct BinNode { /// The state composed of bits. pub state: Bitv, /// The choices represented as bits that can be flipped. pub choices: Bitv } impl BinNode { /// Gets pairs from pair of booleans. pub fn from_pairs(pairs: &[(bool, bool)]) -> BinNode { BinNode { state: pairs.iter().map(|&(a, _)| a).collect(), choices: pairs.iter().map(|&(_, b)| b).collect() } }
/// Call closure for each available choice. #[inline(always)] pub fn with_choices(&self, f: |i: uint|) { for i in range(0, self.choices.len()) .zip(self.choices.iter()) .filter(|&(_, v)| v) .map(|(i, _)| i ) { f(i) } } /// Calls closure for all choices that are not in graph. #[inline(always)] pub fn with_choices_not_in<TAction>( &self, graph: &BinGraph<TAction>, f: |i: uint| ) { self.with_choices(|i| if !graph.contains_choice(self, i) { f(i) }) } }
random_line_split
binnode.rs
use std::collections::Bitv; use BinGraph; /// Contains a binary state and the choices. #[deriving(PartialEq, Eq, Show, Clone)] pub struct BinNode { /// The state composed of bits. pub state: Bitv, /// The choices represented as bits that can be flipped. pub choices: Bitv } impl BinNode { /// Gets pairs from pair of booleans. pub fn from_pairs(pairs: &[(bool, bool)]) -> BinNode
/// Call closure for each available choice. #[inline(always)] pub fn with_choices(&self, f: |i: uint|) { for i in range(0, self.choices.len()) .zip(self.choices.iter()) .filter(|&(_, v)| v) .map(|(i, _)| i ) { f(i) } } /// Calls closure for all choices that are not in graph. #[inline(always)] pub fn with_choices_not_in<TAction>( &self, graph: &BinGraph<TAction>, f: |i: uint| ) { self.with_choices(|i| if !graph.contains_choice(self, i) { f(i) }) } }
{ BinNode { state: pairs.iter().map(|&(a, _)| a).collect(), choices: pairs.iter().map(|&(_, b)| b).collect() } }
identifier_body
binnode.rs
use std::collections::Bitv; use BinGraph; /// Contains a binary state and the choices. #[deriving(PartialEq, Eq, Show, Clone)] pub struct BinNode { /// The state composed of bits. pub state: Bitv, /// The choices represented as bits that can be flipped. pub choices: Bitv } impl BinNode { /// Gets pairs from pair of booleans. pub fn from_pairs(pairs: &[(bool, bool)]) -> BinNode { BinNode { state: pairs.iter().map(|&(a, _)| a).collect(), choices: pairs.iter().map(|&(_, b)| b).collect() } } /// Call closure for each available choice. #[inline(always)] pub fn
(&self, f: |i: uint|) { for i in range(0, self.choices.len()) .zip(self.choices.iter()) .filter(|&(_, v)| v) .map(|(i, _)| i ) { f(i) } } /// Calls closure for all choices that are not in graph. #[inline(always)] pub fn with_choices_not_in<TAction>( &self, graph: &BinGraph<TAction>, f: |i: uint| ) { self.with_choices(|i| if !graph.contains_choice(self, i) { f(i) }) } }
with_choices
identifier_name
[postID].tsx
import { css } from "@emotion/react"; import styled from "@emotion/styled"; import { GetStaticPaths, GetStaticProps } from "next"; import { IMDXSource } from "next-mdx-remote"; import hydrate from "next-mdx-remote/hydrate"; import renderToString from "next-mdx-remote/render-to-string"; import Head from "next/head"; import Image from "next/image"; import Link from "next/link"; import React from "react"; import rehypeKatex from "rehype-katex"; import remarkMath from "remark-math"; import { PostComments } from "~src/components/PostComments"; import { getAllPosts, getPostByID, IPost } from "~src/lib/content/posts"; import { formatDate } from "~src/lib/formatDate"; import { mdxComponents } from "~src/lib/mdxComponents"; import { katexCss } from "~src/lib/styles/katexCss"; import { mobileOnly } from "~src/lib/styles/mobileOnly"; interface IProps { source: IMDXSource; post: IPost; } const PostUnder = styled.div` color: #3271a7; text-align: center; line-height: 10px; margin-bottom: 60px; ${mobileOnly(css` margin-bottom: 30px; `)} font-weight: normal; `; const Post: React.FC<IProps> = ({ source, post }) => { // TODO(igm): the client likes to hydrate things differently than the // server due to Emotion. We need to set up an emotion cache // per-request to share the styles between frontend and backend. // Not too important const content = hydrate(source, { components: mdxComponents }); return ( <PostWrapper post={post}> <Head> <title>{post.title} | Ian Macalinao</title> <meta property="twitter:title" content={post.title} /> <meta property="og:type" content="article" /> <meta property="og:article:author" content="Ian Macalinao" /> <meta property="twitter:site" content="@simplyianm" /> <meta property="twitter:creator" content="@simplyianm" /> <meta name="author" content="Ian Macalinao, me@ian.pw" /> <meta property="og:article:published_time" content={`${new Date(post.publishedAt).toISOString()}`} /> {post.tags.map((tag) => ( <meta key={tag} property="og:article:tag" content={tag} /> ))} {post.tags.length > 0 && ( <meta name="keywords" content={post.tags.join(", ")} /> )} <meta property="og:title" content={post.title} /> <meta property="og:url" content={`https://ian.pw${post.path}`} /> <meta property="twitter:url" content={`https://ian.pw${post.path}`} /> {post.description && ( <> <meta name="description" content={post.description} /> <meta property="og:description" content={post.description} /> <meta property="twitter:description" content={post.description} /> </> )} {post.banner ? ( <> <meta property="og:image" content={post.banner.src} /> <meta property="og:image:width" content={post.banner.width.toString()} /> <meta property="og:image:height" content={post.banner.height.toString()} /> <meta property="og:image:url" content={post.banner.src} /> <meta property="twitter:image" content={post.banner.src} /> <meta property="twitter:image:alt" content={post.banner.alt} /> <meta property="twitter:card" content="summary_large_image" /> </> ) : ( // If no banner is present, still display a card <meta name="twitter:card" content="summary" /> )} </Head> <h1 css={css` margin-bottom: 30px; ${mobileOnly(css` text-align: center; `)} `} > {post.title} </h1> <PostUnder> <p> by{" "} <Link href="/"> <a>Ian Macalinao</a> </Link>{" "} on {formatDate(new Date(post.publishedAt))} </p> </PostUnder> <div id="post"> {post.incomplete && ( <em> Note: This section is incomplete. You can help finish it <a href="https://github.com/macalinao/ian.pw/blob/master/$path$" target="_blank" > here </a> . </em> )} {post.banner && ( <Image alt={post.banner.alt} src={post.banner.src} width={post.banner.width} height={post.banner.height} /> )} {content} </div> <Thanks> <p> Thanks for reading! Have any questions, comments, or suggestions? Feel free to use the comment section below or email me at{" "} <a href="mailto:blog@igm.pub">blog@igm.pub</a> and I'll do my best to respond. </p> <p> Alternatively, you can view the source of the post{" "} <a href={`https://github.com/macalinao/ian.pw/blob/master/content/posts/${post.id}.md`} target="_blank" > here </a>{" "} and send a pull request. </p> </Thanks> <PostComments post={post} /> </PostWrapper> ); }; const PostWrapper = styled.div<{ post: IPost }>` ${(props) => props.post.hasMath && katexCss} h1, h2 { line-height: 1.3; } h3 { line-height: 1.5; } h2, h3 { margin-top: 50px; } ${mobileOnly(css` h2 { font-size: 22px; } h3 { font-size: 18px; } h2 { margin-top: 25px; } h3 { margin-top: 12px; } p, li { font-size: 16px; line-height: 1.5em; } `)} .math.math-display { overflow-x: scroll; } .footnotes { margin-top: 60px; ol { margin: 40px 0; } li { font-size: 18px; } color: #454545; border-top: 1px solid #ccc; hr { display: none; } .footnote-backref { margin-left: 8px; font-size: 14px; } } `; const Thanks = styled.div` margin: 3em auto; border: 1px solid #eee; padding: 20px 40px; background-color: #fafaff; color: #656565; p { font-size: 18px; } `; export const getStaticPaths: GetStaticPaths = async () => { const posts = await getAllPosts(); return { paths: posts.map((post) => post.path), fallback: "blocking", }; }; export const getStaticProps: GetStaticProps< IProps, { postID: string } > = async (req) => { const postID = req.params?.postID; if (!postID) { return { notFound: true, }; } const postIDNoSuffix = postID.split(".html")[0]; if (!postIDNoSuffix) { return { notFound: true, }; } const post = await getPostByID(postIDNoSuffix); if (postID.endsWith(".html"))
const mdxSource = await renderToString(post.content, { components: mdxComponents, mdxOptions: { remarkPlugins: [remarkMath], rehypePlugins: [rehypeKatex], }, }); return { props: { source: mdxSource, post } }; }; export default Post;
{ return { redirect: { permanent: true, destination: post.path, }, }; }
conditional_block
[postID].tsx
import { css } from "@emotion/react"; import styled from "@emotion/styled"; import { GetStaticPaths, GetStaticProps } from "next"; import { IMDXSource } from "next-mdx-remote"; import hydrate from "next-mdx-remote/hydrate"; import renderToString from "next-mdx-remote/render-to-string"; import Head from "next/head"; import Image from "next/image"; import Link from "next/link"; import React from "react"; import rehypeKatex from "rehype-katex"; import remarkMath from "remark-math"; import { PostComments } from "~src/components/PostComments"; import { getAllPosts, getPostByID, IPost } from "~src/lib/content/posts"; import { formatDate } from "~src/lib/formatDate"; import { mdxComponents } from "~src/lib/mdxComponents"; import { katexCss } from "~src/lib/styles/katexCss"; import { mobileOnly } from "~src/lib/styles/mobileOnly"; interface IProps { source: IMDXSource; post: IPost; } const PostUnder = styled.div` color: #3271a7; text-align: center; line-height: 10px; margin-bottom: 60px; ${mobileOnly(css` margin-bottom: 30px; `)} font-weight: normal; `; const Post: React.FC<IProps> = ({ source, post }) => { // TODO(igm): the client likes to hydrate things differently than the // server due to Emotion. We need to set up an emotion cache // per-request to share the styles between frontend and backend. // Not too important const content = hydrate(source, { components: mdxComponents }); return ( <PostWrapper post={post}> <Head> <title>{post.title} | Ian Macalinao</title> <meta property="twitter:title" content={post.title} /> <meta property="og:type" content="article" /> <meta property="og:article:author" content="Ian Macalinao" /> <meta property="twitter:site" content="@simplyianm" /> <meta property="twitter:creator" content="@simplyianm" /> <meta name="author" content="Ian Macalinao, me@ian.pw" /> <meta property="og:article:published_time" content={`${new Date(post.publishedAt).toISOString()}`} /> {post.tags.map((tag) => ( <meta key={tag} property="og:article:tag" content={tag} /> ))} {post.tags.length > 0 && ( <meta name="keywords" content={post.tags.join(", ")} /> )} <meta property="og:title" content={post.title} /> <meta property="og:url" content={`https://ian.pw${post.path}`} /> <meta property="twitter:url" content={`https://ian.pw${post.path}`} /> {post.description && ( <> <meta name="description" content={post.description} /> <meta property="og:description" content={post.description} /> <meta property="twitter:description" content={post.description} /> </> )} {post.banner ? ( <> <meta property="og:image" content={post.banner.src} /> <meta property="og:image:width" content={post.banner.width.toString()} /> <meta property="og:image:height" content={post.banner.height.toString()} />
</> ) : ( // If no banner is present, still display a card <meta name="twitter:card" content="summary" /> )} </Head> <h1 css={css` margin-bottom: 30px; ${mobileOnly(css` text-align: center; `)} `} > {post.title} </h1> <PostUnder> <p> by{" "} <Link href="/"> <a>Ian Macalinao</a> </Link>{" "} on {formatDate(new Date(post.publishedAt))} </p> </PostUnder> <div id="post"> {post.incomplete && ( <em> Note: This section is incomplete. You can help finish it <a href="https://github.com/macalinao/ian.pw/blob/master/$path$" target="_blank" > here </a> . </em> )} {post.banner && ( <Image alt={post.banner.alt} src={post.banner.src} width={post.banner.width} height={post.banner.height} /> )} {content} </div> <Thanks> <p> Thanks for reading! Have any questions, comments, or suggestions? Feel free to use the comment section below or email me at{" "} <a href="mailto:blog@igm.pub">blog@igm.pub</a> and I'll do my best to respond. </p> <p> Alternatively, you can view the source of the post{" "} <a href={`https://github.com/macalinao/ian.pw/blob/master/content/posts/${post.id}.md`} target="_blank" > here </a>{" "} and send a pull request. </p> </Thanks> <PostComments post={post} /> </PostWrapper> ); }; const PostWrapper = styled.div<{ post: IPost }>` ${(props) => props.post.hasMath && katexCss} h1, h2 { line-height: 1.3; } h3 { line-height: 1.5; } h2, h3 { margin-top: 50px; } ${mobileOnly(css` h2 { font-size: 22px; } h3 { font-size: 18px; } h2 { margin-top: 25px; } h3 { margin-top: 12px; } p, li { font-size: 16px; line-height: 1.5em; } `)} .math.math-display { overflow-x: scroll; } .footnotes { margin-top: 60px; ol { margin: 40px 0; } li { font-size: 18px; } color: #454545; border-top: 1px solid #ccc; hr { display: none; } .footnote-backref { margin-left: 8px; font-size: 14px; } } `; const Thanks = styled.div` margin: 3em auto; border: 1px solid #eee; padding: 20px 40px; background-color: #fafaff; color: #656565; p { font-size: 18px; } `; export const getStaticPaths: GetStaticPaths = async () => { const posts = await getAllPosts(); return { paths: posts.map((post) => post.path), fallback: "blocking", }; }; export const getStaticProps: GetStaticProps< IProps, { postID: string } > = async (req) => { const postID = req.params?.postID; if (!postID) { return { notFound: true, }; } const postIDNoSuffix = postID.split(".html")[0]; if (!postIDNoSuffix) { return { notFound: true, }; } const post = await getPostByID(postIDNoSuffix); if (postID.endsWith(".html")) { return { redirect: { permanent: true, destination: post.path, }, }; } const mdxSource = await renderToString(post.content, { components: mdxComponents, mdxOptions: { remarkPlugins: [remarkMath], rehypePlugins: [rehypeKatex], }, }); return { props: { source: mdxSource, post } }; }; export default Post;
<meta property="og:image:url" content={post.banner.src} /> <meta property="twitter:image" content={post.banner.src} /> <meta property="twitter:image:alt" content={post.banner.alt} /> <meta property="twitter:card" content="summary_large_image" />
random_line_split
Shop.js
import React from 'react' import { moneyFormat } from '../../../modules/helpers' import './shop.scss' import { Link } from 'react-router' const Product = ({id, price, name, description, onAddToCart}) => ( <div className="product-box"> <h3>{name}</h3> <p>{description}</p> <section className="bottom"> <div className="price">{moneyFormat(price)}</div> <button className="add-to-cart" onClick={ () => onAddToCart( {product: {id, name, price}} ) } > Add To Cart </button> </section> </div>
) export default class Shop extends React.Component{ constructor(props){ super(props); props.getProducts(); props.getUsers(); } componentDidUpdate(){ if(this.props.state.shop.displayNotice){ setTimeout( () => this.props.destroyNoticeMsg(), 3500 ) } } selectUser = (e) => { const { users } = this.props.state.shop; for(let i = 0; i < users.length; i++){ if(users[i].id === e.target.value){ this.props.setActiveUser(users[i]) break } } } render(){ const {products, users, displayNotice, noticeMsg} = this.props.state.shop; // console.log(this.props.state.shop); return ( <div className="shop"> {users && ( <div className="test-user-select"> Test As: <select value={this.props.state.shop.user.id} onChange={ this.selectUser }> <option value="guest">Guest</option> {users.map( (user) => ( <option key={user.id} value={ user.id }>{user.username}</option> ))} </select> </div>)} {displayNotice && ( <div className="notice">{ noticeMsg }</div> )} <div className="checkout-wrapper"> <Link to="/checkout" className="checkout-btn">Checkout Now</Link> </div> <div className="products-wrapper center-block"> {products && products.map((p) => ( <Product key={p.id} {...p} onAddToCart={ this.props.addToCart }/> ))} </div> </div> ); } }
random_line_split
Shop.js
import React from 'react' import { moneyFormat } from '../../../modules/helpers' import './shop.scss' import { Link } from 'react-router' const Product = ({id, price, name, description, onAddToCart}) => ( <div className="product-box"> <h3>{name}</h3> <p>{description}</p> <section className="bottom"> <div className="price">{moneyFormat(price)}</div> <button className="add-to-cart" onClick={ () => onAddToCart( {product: {id, name, price}} ) } > Add To Cart </button> </section> </div> ) export default class Shop extends React.Component{ constructor(props){ super(props); props.getProducts(); props.getUsers(); } componentDidUpdate(){ if(this.props.state.shop.displayNotice){ setTimeout( () => this.props.destroyNoticeMsg(), 3500 ) } } selectUser = (e) => { const { users } = this.props.state.shop; for(let i = 0; i < users.length; i++)
} render(){ const {products, users, displayNotice, noticeMsg} = this.props.state.shop; // console.log(this.props.state.shop); return ( <div className="shop"> {users && ( <div className="test-user-select"> Test As: <select value={this.props.state.shop.user.id} onChange={ this.selectUser }> <option value="guest">Guest</option> {users.map( (user) => ( <option key={user.id} value={ user.id }>{user.username}</option> ))} </select> </div>)} {displayNotice && ( <div className="notice">{ noticeMsg }</div> )} <div className="checkout-wrapper"> <Link to="/checkout" className="checkout-btn">Checkout Now</Link> </div> <div className="products-wrapper center-block"> {products && products.map((p) => ( <Product key={p.id} {...p} onAddToCart={ this.props.addToCart }/> ))} </div> </div> ); } }
{ if(users[i].id === e.target.value){ this.props.setActiveUser(users[i]) break } }
conditional_block
Shop.js
import React from 'react' import { moneyFormat } from '../../../modules/helpers' import './shop.scss' import { Link } from 'react-router' const Product = ({id, price, name, description, onAddToCart}) => ( <div className="product-box"> <h3>{name}</h3> <p>{description}</p> <section className="bottom"> <div className="price">{moneyFormat(price)}</div> <button className="add-to-cart" onClick={ () => onAddToCart( {product: {id, name, price}} ) } > Add To Cart </button> </section> </div> ) export default class Shop extends React.Component{ constructor(props){ super(props); props.getProducts(); props.getUsers(); } componentDidUpdate(){ if(this.props.state.shop.displayNotice){ setTimeout( () => this.props.destroyNoticeMsg(), 3500 ) } } selectUser = (e) => { const { users } = this.props.state.shop; for(let i = 0; i < users.length; i++){ if(users[i].id === e.target.value){ this.props.setActiveUser(users[i]) break } } } render()
}
{ const {products, users, displayNotice, noticeMsg} = this.props.state.shop; // console.log(this.props.state.shop); return ( <div className="shop"> {users && ( <div className="test-user-select"> Test As: <select value={this.props.state.shop.user.id} onChange={ this.selectUser }> <option value="guest">Guest</option> {users.map( (user) => ( <option key={user.id} value={ user.id }>{user.username}</option> ))} </select> </div>)} {displayNotice && ( <div className="notice">{ noticeMsg }</div> )} <div className="checkout-wrapper"> <Link to="/checkout" className="checkout-btn">Checkout Now</Link> </div> <div className="products-wrapper center-block"> {products && products.map((p) => ( <Product key={p.id} {...p} onAddToCart={ this.props.addToCart }/> ))} </div> </div> ); }
identifier_body
Shop.js
import React from 'react' import { moneyFormat } from '../../../modules/helpers' import './shop.scss' import { Link } from 'react-router' const Product = ({id, price, name, description, onAddToCart}) => ( <div className="product-box"> <h3>{name}</h3> <p>{description}</p> <section className="bottom"> <div className="price">{moneyFormat(price)}</div> <button className="add-to-cart" onClick={ () => onAddToCart( {product: {id, name, price}} ) } > Add To Cart </button> </section> </div> ) export default class Shop extends React.Component{
(props){ super(props); props.getProducts(); props.getUsers(); } componentDidUpdate(){ if(this.props.state.shop.displayNotice){ setTimeout( () => this.props.destroyNoticeMsg(), 3500 ) } } selectUser = (e) => { const { users } = this.props.state.shop; for(let i = 0; i < users.length; i++){ if(users[i].id === e.target.value){ this.props.setActiveUser(users[i]) break } } } render(){ const {products, users, displayNotice, noticeMsg} = this.props.state.shop; // console.log(this.props.state.shop); return ( <div className="shop"> {users && ( <div className="test-user-select"> Test As: <select value={this.props.state.shop.user.id} onChange={ this.selectUser }> <option value="guest">Guest</option> {users.map( (user) => ( <option key={user.id} value={ user.id }>{user.username}</option> ))} </select> </div>)} {displayNotice && ( <div className="notice">{ noticeMsg }</div> )} <div className="checkout-wrapper"> <Link to="/checkout" className="checkout-btn">Checkout Now</Link> </div> <div className="products-wrapper center-block"> {products && products.map((p) => ( <Product key={p.id} {...p} onAddToCart={ this.props.addToCart }/> ))} </div> </div> ); } }
constructor
identifier_name
node_void_ptr.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/. */ //! CSS library requires that DOM nodes be convertable to *c_void through this trait extern mod netsurfcss; use dom::node::AbstractNode; use core::cast; // FIXME: Rust #3908. rust-css can't reexport VoidPtrLike use css::node_void_ptr::netsurfcss::util::VoidPtrLike; impl VoidPtrLike for AbstractNode { fn
(node: *libc::c_void) -> AbstractNode { assert!(node.is_not_null()); unsafe { cast::transmute(node) } } fn to_void_ptr(&self) -> *libc::c_void { unsafe { cast::transmute(*self) } } }
from_void_ptr
identifier_name
node_void_ptr.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/. */ //! CSS library requires that DOM nodes be convertable to *c_void through this trait extern mod netsurfcss; use dom::node::AbstractNode; use core::cast; // FIXME: Rust #3908. rust-css can't reexport VoidPtrLike use css::node_void_ptr::netsurfcss::util::VoidPtrLike; impl VoidPtrLike for AbstractNode { fn from_void_ptr(node: *libc::c_void) -> AbstractNode { assert!(node.is_not_null()); unsafe { cast::transmute(node) } } fn to_void_ptr(&self) -> *libc::c_void
}
{ unsafe { cast::transmute(*self) } }
identifier_body
node_void_ptr.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/. */ //! CSS library requires that DOM nodes be convertable to *c_void through this trait extern mod netsurfcss; use dom::node::AbstractNode; use core::cast; // FIXME: Rust #3908. rust-css can't reexport VoidPtrLike use css::node_void_ptr::netsurfcss::util::VoidPtrLike;
fn from_void_ptr(node: *libc::c_void) -> AbstractNode { assert!(node.is_not_null()); unsafe { cast::transmute(node) } } fn to_void_ptr(&self) -> *libc::c_void { unsafe { cast::transmute(*self) } } }
impl VoidPtrLike for AbstractNode {
random_line_split
lmmsg.rs
// Copyright © 2015-2017 winapi-rs developers // 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. // All files in the project carrying such notice may not be copied, modified, or distributed // except according to those terms. //! This file contains structures, function prototypes, and definitions for the NetMessage API use shared::lmcons::NET_API_STATUS; use shared::minwindef::{DWORD, LPBYTE, LPDWORD}; use um::winnt::{LPCWSTR, LPWSTR}; extern "system" { pub fn NetMessageNameAdd( servername: LPCWSTR, msgname: LPCWSTR, ) -> NET_API_STATUS; pub fn NetMessageNameEnum( servername: LPCWSTR, level: DWORD, bufptr: *mut LPBYTE, prefmaxlen: DWORD, entriesread: LPDWORD, totalentries: LPDWORD, resumehandle: LPDWORD, ) -> NET_API_STATUS; pub fn NetMessageNameGetInfo( servername: LPCWSTR, msgname: LPCWSTR, level: DWORD, bufptr: *mut LPBYTE, ) -> NET_API_STATUS; pub fn NetMessageNameDel( servername: LPCWSTR, msgname: LPCWSTR, ) -> NET_API_STATUS; pub fn NetMessageBufferSend( servername: LPCWSTR, msgname: LPCWSTR, fromname: LPCWSTR, buf: LPBYTE, buflen: DWORD, ) -> NET_API_STATUS; } STRUCT!{struct MSG_INFO_0 { msgi0_name: LPWSTR, }} pub type PMSG_INFO_0 = *mut MSG_INFO_0; pub type LPMSG_INFO_0 = *mut MSG_INFO_0; STRUCT!{struct MSG_INFO_1 { msgi1_name: LPWSTR, msgi1_forward_flag: DWORD, msgi1_forward: LPWSTR,
pub type LPMSG_INFO_1 = *mut MSG_INFO_1; pub const MSGNAME_NOT_FORWARDED: DWORD = 0; pub const MSGNAME_FORWARDED_TO: DWORD = 0x04; pub const MSGNAME_FORWARDED_FROM: DWORD = 0x10;
}} pub type PMSG_INFO_1 = *mut MSG_INFO_1;
random_line_split
my-children-controller.js
/* global _, angular */ 'use strict'; function myChildrenCtrl ($scope, $state, $translate, ownProfile, cdUsersService) { $scope.parentProfileData = ownProfile.data; $scope.tabs = []; function loadChildrenTabs () { $scope.tabs = []; cdUsersService.loadChildrenForUser($scope.parentProfileData.userId, function (children) { $scope.children = _.sortBy(children, [ function (child) { return child.name.toLowerCase(); } ]); $scope.tabs = $scope.children.map(function (child) { return { state: 'my-children.child', stateParams: {id: child.userId}, tabImage: '/api/2.0/profiles/' + child.id + '/avatar_img', tabTitle: child.name, tabSubTitle: child.alias }; }); $scope.tabs.push({ state: 'my-children.add', tabImage: '/img/avatars/avatar.png', tabTitle: $translate.instant('Add Child') }); }); } loadChildrenTabs(); $scope.$on('$stateChangeStart', function (e, toState, params) { if (toState.name === 'my-children.child') { var childLoaded = _.some($scope.children, function (child) { return child.userId === params.id; }); if (!childLoaded)
} }); } angular.module('cpZenPlatform') .controller('my-children-controller', ['$scope', '$state', '$translate', 'ownProfile', 'cdUsersService', myChildrenCtrl]);
{ loadChildrenTabs(); }
conditional_block
my-children-controller.js
/* global _, angular */ 'use strict'; function myChildrenCtrl ($scope, $state, $translate, ownProfile, cdUsersService) { $scope.parentProfileData = ownProfile.data; $scope.tabs = []; function
() { $scope.tabs = []; cdUsersService.loadChildrenForUser($scope.parentProfileData.userId, function (children) { $scope.children = _.sortBy(children, [ function (child) { return child.name.toLowerCase(); } ]); $scope.tabs = $scope.children.map(function (child) { return { state: 'my-children.child', stateParams: {id: child.userId}, tabImage: '/api/2.0/profiles/' + child.id + '/avatar_img', tabTitle: child.name, tabSubTitle: child.alias }; }); $scope.tabs.push({ state: 'my-children.add', tabImage: '/img/avatars/avatar.png', tabTitle: $translate.instant('Add Child') }); }); } loadChildrenTabs(); $scope.$on('$stateChangeStart', function (e, toState, params) { if (toState.name === 'my-children.child') { var childLoaded = _.some($scope.children, function (child) { return child.userId === params.id; }); if (!childLoaded) { loadChildrenTabs(); } } }); } angular.module('cpZenPlatform') .controller('my-children-controller', ['$scope', '$state', '$translate', 'ownProfile', 'cdUsersService', myChildrenCtrl]);
loadChildrenTabs
identifier_name
my-children-controller.js
/* global _, angular */ 'use strict'; function myChildrenCtrl ($scope, $state, $translate, ownProfile, cdUsersService) { $scope.parentProfileData = ownProfile.data; $scope.tabs = []; function loadChildrenTabs ()
loadChildrenTabs(); $scope.$on('$stateChangeStart', function (e, toState, params) { if (toState.name === 'my-children.child') { var childLoaded = _.some($scope.children, function (child) { return child.userId === params.id; }); if (!childLoaded) { loadChildrenTabs(); } } }); } angular.module('cpZenPlatform') .controller('my-children-controller', ['$scope', '$state', '$translate', 'ownProfile', 'cdUsersService', myChildrenCtrl]);
{ $scope.tabs = []; cdUsersService.loadChildrenForUser($scope.parentProfileData.userId, function (children) { $scope.children = _.sortBy(children, [ function (child) { return child.name.toLowerCase(); } ]); $scope.tabs = $scope.children.map(function (child) { return { state: 'my-children.child', stateParams: {id: child.userId}, tabImage: '/api/2.0/profiles/' + child.id + '/avatar_img', tabTitle: child.name, tabSubTitle: child.alias }; }); $scope.tabs.push({ state: 'my-children.add', tabImage: '/img/avatars/avatar.png', tabTitle: $translate.instant('Add Child') }); }); }
identifier_body
my-children-controller.js
/* global _, angular */ 'use strict'; function myChildrenCtrl ($scope, $state, $translate, ownProfile, cdUsersService) { $scope.parentProfileData = ownProfile.data; $scope.tabs = []; function loadChildrenTabs () { $scope.tabs = []; cdUsersService.loadChildrenForUser($scope.parentProfileData.userId, function (children) { $scope.children = _.sortBy(children, [ function (child) { return child.name.toLowerCase(); } ]); $scope.tabs = $scope.children.map(function (child) { return { state: 'my-children.child', stateParams: {id: child.userId}, tabImage: '/api/2.0/profiles/' + child.id + '/avatar_img', tabTitle: child.name, tabSubTitle: child.alias }; }); $scope.tabs.push({ state: 'my-children.add', tabImage: '/img/avatars/avatar.png', tabTitle: $translate.instant('Add Child') }); }); } loadChildrenTabs(); $scope.$on('$stateChangeStart', function (e, toState, params) { if (toState.name === 'my-children.child') { var childLoaded = _.some($scope.children, function (child) {
if (!childLoaded) { loadChildrenTabs(); } } }); } angular.module('cpZenPlatform') .controller('my-children-controller', ['$scope', '$state', '$translate', 'ownProfile', 'cdUsersService', myChildrenCtrl]);
return child.userId === params.id; });
random_line_split
qr_scanner.py
from kivy.app import App from kivy.factory import Factory from kivy.lang import Builder Factory.register('QRScanner', module='electrum.gui.kivy.qr_scanner') class QrScannerDialog(Factory.AnimatedPopup): __events__ = ('on_complete', ) def on_symbols(self, instance, value): instance.stop() self.dismiss() data = value[0].data self.dispatch('on_complete', data) def on_complete(self, x): ''' Default Handler for on_complete event. ''' print(x) Builder.load_string(''' <QrScannerDialog> title: _(\ '[size=18dp]Hold your QRCode up to the camera[/size][size=7dp]\\n[/size]') title_size: '24sp' border: 7, 7, 7, 7 size_hint: None, None size: '340dp', '290dp' pos_hint: {'center_y': .53} #separator_color: .89, .89, .89, 1
#separator_height: '1.2dp' #title_color: .437, .437, .437, 1 #background: 'atlas://electrum/gui/kivy/theming/light/dialog' on_activate: qrscr.start() qrscr.size = self.size on_deactivate: qrscr.stop() QRScanner: id: qrscr on_symbols: root.on_symbols(*args) ''')
random_line_split
qr_scanner.py
from kivy.app import App from kivy.factory import Factory from kivy.lang import Builder Factory.register('QRScanner', module='electrum.gui.kivy.qr_scanner') class QrScannerDialog(Factory.AnimatedPopup): __events__ = ('on_complete', ) def
(self, instance, value): instance.stop() self.dismiss() data = value[0].data self.dispatch('on_complete', data) def on_complete(self, x): ''' Default Handler for on_complete event. ''' print(x) Builder.load_string(''' <QrScannerDialog> title: _(\ '[size=18dp]Hold your QRCode up to the camera[/size][size=7dp]\\n[/size]') title_size: '24sp' border: 7, 7, 7, 7 size_hint: None, None size: '340dp', '290dp' pos_hint: {'center_y': .53} #separator_color: .89, .89, .89, 1 #separator_height: '1.2dp' #title_color: .437, .437, .437, 1 #background: 'atlas://electrum/gui/kivy/theming/light/dialog' on_activate: qrscr.start() qrscr.size = self.size on_deactivate: qrscr.stop() QRScanner: id: qrscr on_symbols: root.on_symbols(*args) ''')
on_symbols
identifier_name
qr_scanner.py
from kivy.app import App from kivy.factory import Factory from kivy.lang import Builder Factory.register('QRScanner', module='electrum.gui.kivy.qr_scanner') class QrScannerDialog(Factory.AnimatedPopup):
Builder.load_string(''' <QrScannerDialog> title: _(\ '[size=18dp]Hold your QRCode up to the camera[/size][size=7dp]\\n[/size]') title_size: '24sp' border: 7, 7, 7, 7 size_hint: None, None size: '340dp', '290dp' pos_hint: {'center_y': .53} #separator_color: .89, .89, .89, 1 #separator_height: '1.2dp' #title_color: .437, .437, .437, 1 #background: 'atlas://electrum/gui/kivy/theming/light/dialog' on_activate: qrscr.start() qrscr.size = self.size on_deactivate: qrscr.stop() QRScanner: id: qrscr on_symbols: root.on_symbols(*args) ''')
__events__ = ('on_complete', ) def on_symbols(self, instance, value): instance.stop() self.dismiss() data = value[0].data self.dispatch('on_complete', data) def on_complete(self, x): ''' Default Handler for on_complete event. ''' print(x)
identifier_body
test_events.py
"""This module tests events that are invoked by Cloud/Infra VMs.""" import fauxfactory import pytest from cfme import test_requirements from cfme.cloud.provider import CloudProvider from cfme.cloud.provider.gce import GCEProvider from cfme.control.explorer.policies import VMControlPolicy from cfme.infrastructure.provider import InfraProvider from cfme.infrastructure.provider.kubevirt import KubeVirtProvider from cfme.markers.env_markers.provider import providers from cfme.utils.providers import ProviderFilter from cfme.utils.wait import wait_for all_prov = ProviderFilter(classes=[InfraProvider, CloudProvider], required_fields=['provisioning', 'events']) excluded = ProviderFilter(classes=[KubeVirtProvider], inverted=True) pytestmark = [ pytest.mark.usefixtures('uses_infra_providers', 'uses_cloud_providers'), pytest.mark.tier(2), pytest.mark.provider(gen_func=providers, filters=[all_prov, excluded], scope='module'), test_requirements.events, ] @pytest.fixture(scope="function") def vm_crud(provider, setup_provider_modscope, small_template_modscope): template = small_template_modscope base_name = 'test-events-' if provider.one_of(GCEProvider) else 'test_events_' vm_name = fauxfactory.gen_alpha(20, start=base_name).lower() collection = provider.appliance.provider_based_collection(provider) vm = collection.instantiate(vm_name, provider, template_name=template.name) yield vm vm.cleanup_on_provider() @pytest.mark.rhv2 def test_vm_create(request, appliance, vm_crud, provider, register_event): """ Test whether vm_create_complete event is emitted. Prerequisities: * A provider that is set up and able to deploy VMs Steps: * Create a Control setup (action, policy, profile) that apply a tag on a VM when ``VM Create Complete`` event comes * Deploy the VM outside of CFME (directly in the provider) * Refresh provider relationships and wait for VM to appear
Polarion: assignee: jdupuy casecomponent: Events caseimportance: high initialEstimate: 1/8h """ action = appliance.collections.actions.create( fauxfactory.gen_alpha(), "Tag", dict(tag=("My Company Tags", "Environment", "Development"))) request.addfinalizer(action.delete) policy = appliance.collections.policies.create( VMControlPolicy, fauxfactory.gen_alpha() ) request.addfinalizer(policy.delete) policy.assign_events("VM Create Complete") @request.addfinalizer def _cleanup(): policy.unassign_events("VM Create Complete") policy.assign_actions_to_event("VM Create Complete", action) profile = appliance.collections.policy_profiles.create( fauxfactory.gen_alpha(), policies=[policy]) request.addfinalizer(profile.delete) provider.assign_policy_profiles(profile.description) request.addfinalizer(lambda: provider.unassign_policy_profiles(profile.description)) register_event(target_type='VmOrTemplate', target_name=vm_crud.name, event_type='vm_create') vm_crud.create_on_provider(find_in_cfme=True) def _check(): return any(tag.category.display_name == "Environment" and tag.display_name == "Development" for tag in vm_crud.get_tags()) wait_for(_check, num_sec=300, delay=15, message="tags to appear")
* Assert the tag appears. Metadata: test_flag: provision, events
random_line_split
test_events.py
"""This module tests events that are invoked by Cloud/Infra VMs.""" import fauxfactory import pytest from cfme import test_requirements from cfme.cloud.provider import CloudProvider from cfme.cloud.provider.gce import GCEProvider from cfme.control.explorer.policies import VMControlPolicy from cfme.infrastructure.provider import InfraProvider from cfme.infrastructure.provider.kubevirt import KubeVirtProvider from cfme.markers.env_markers.provider import providers from cfme.utils.providers import ProviderFilter from cfme.utils.wait import wait_for all_prov = ProviderFilter(classes=[InfraProvider, CloudProvider], required_fields=['provisioning', 'events']) excluded = ProviderFilter(classes=[KubeVirtProvider], inverted=True) pytestmark = [ pytest.mark.usefixtures('uses_infra_providers', 'uses_cloud_providers'), pytest.mark.tier(2), pytest.mark.provider(gen_func=providers, filters=[all_prov, excluded], scope='module'), test_requirements.events, ] @pytest.fixture(scope="function") def vm_crud(provider, setup_provider_modscope, small_template_modscope): template = small_template_modscope base_name = 'test-events-' if provider.one_of(GCEProvider) else 'test_events_' vm_name = fauxfactory.gen_alpha(20, start=base_name).lower() collection = provider.appliance.provider_based_collection(provider) vm = collection.instantiate(vm_name, provider, template_name=template.name) yield vm vm.cleanup_on_provider() @pytest.mark.rhv2 def test_vm_create(request, appliance, vm_crud, provider, register_event): """ Test whether vm_create_complete event is emitted. Prerequisities: * A provider that is set up and able to deploy VMs Steps: * Create a Control setup (action, policy, profile) that apply a tag on a VM when ``VM Create Complete`` event comes * Deploy the VM outside of CFME (directly in the provider) * Refresh provider relationships and wait for VM to appear * Assert the tag appears. Metadata: test_flag: provision, events Polarion: assignee: jdupuy casecomponent: Events caseimportance: high initialEstimate: 1/8h """ action = appliance.collections.actions.create( fauxfactory.gen_alpha(), "Tag", dict(tag=("My Company Tags", "Environment", "Development"))) request.addfinalizer(action.delete) policy = appliance.collections.policies.create( VMControlPolicy, fauxfactory.gen_alpha() ) request.addfinalizer(policy.delete) policy.assign_events("VM Create Complete") @request.addfinalizer def _cleanup(): policy.unassign_events("VM Create Complete") policy.assign_actions_to_event("VM Create Complete", action) profile = appliance.collections.policy_profiles.create( fauxfactory.gen_alpha(), policies=[policy]) request.addfinalizer(profile.delete) provider.assign_policy_profiles(profile.description) request.addfinalizer(lambda: provider.unassign_policy_profiles(profile.description)) register_event(target_type='VmOrTemplate', target_name=vm_crud.name, event_type='vm_create') vm_crud.create_on_provider(find_in_cfme=True) def _check():
wait_for(_check, num_sec=300, delay=15, message="tags to appear")
return any(tag.category.display_name == "Environment" and tag.display_name == "Development" for tag in vm_crud.get_tags())
identifier_body
test_events.py
"""This module tests events that are invoked by Cloud/Infra VMs.""" import fauxfactory import pytest from cfme import test_requirements from cfme.cloud.provider import CloudProvider from cfme.cloud.provider.gce import GCEProvider from cfme.control.explorer.policies import VMControlPolicy from cfme.infrastructure.provider import InfraProvider from cfme.infrastructure.provider.kubevirt import KubeVirtProvider from cfme.markers.env_markers.provider import providers from cfme.utils.providers import ProviderFilter from cfme.utils.wait import wait_for all_prov = ProviderFilter(classes=[InfraProvider, CloudProvider], required_fields=['provisioning', 'events']) excluded = ProviderFilter(classes=[KubeVirtProvider], inverted=True) pytestmark = [ pytest.mark.usefixtures('uses_infra_providers', 'uses_cloud_providers'), pytest.mark.tier(2), pytest.mark.provider(gen_func=providers, filters=[all_prov, excluded], scope='module'), test_requirements.events, ] @pytest.fixture(scope="function") def vm_crud(provider, setup_provider_modscope, small_template_modscope): template = small_template_modscope base_name = 'test-events-' if provider.one_of(GCEProvider) else 'test_events_' vm_name = fauxfactory.gen_alpha(20, start=base_name).lower() collection = provider.appliance.provider_based_collection(provider) vm = collection.instantiate(vm_name, provider, template_name=template.name) yield vm vm.cleanup_on_provider() @pytest.mark.rhv2 def test_vm_create(request, appliance, vm_crud, provider, register_event): """ Test whether vm_create_complete event is emitted. Prerequisities: * A provider that is set up and able to deploy VMs Steps: * Create a Control setup (action, policy, profile) that apply a tag on a VM when ``VM Create Complete`` event comes * Deploy the VM outside of CFME (directly in the provider) * Refresh provider relationships and wait for VM to appear * Assert the tag appears. Metadata: test_flag: provision, events Polarion: assignee: jdupuy casecomponent: Events caseimportance: high initialEstimate: 1/8h """ action = appliance.collections.actions.create( fauxfactory.gen_alpha(), "Tag", dict(tag=("My Company Tags", "Environment", "Development"))) request.addfinalizer(action.delete) policy = appliance.collections.policies.create( VMControlPolicy, fauxfactory.gen_alpha() ) request.addfinalizer(policy.delete) policy.assign_events("VM Create Complete") @request.addfinalizer def _cleanup(): policy.unassign_events("VM Create Complete") policy.assign_actions_to_event("VM Create Complete", action) profile = appliance.collections.policy_profiles.create( fauxfactory.gen_alpha(), policies=[policy]) request.addfinalizer(profile.delete) provider.assign_policy_profiles(profile.description) request.addfinalizer(lambda: provider.unassign_policy_profiles(profile.description)) register_event(target_type='VmOrTemplate', target_name=vm_crud.name, event_type='vm_create') vm_crud.create_on_provider(find_in_cfme=True) def
(): return any(tag.category.display_name == "Environment" and tag.display_name == "Development" for tag in vm_crud.get_tags()) wait_for(_check, num_sec=300, delay=15, message="tags to appear")
_check
identifier_name
util.js
//@ sourceMappingURL=util.map // Generated by CoffeeScript 1.6.1 var Util, semver; semver = require('semver'); Util = (function() { function Util() {} Util.convertObjectKeysToUnderscores = function(obj) { var item, key, newKey, newObj, value; newObj = {}; for (key in obj) { value = obj[key]; newKey = Util.toUnderscore(key); if (value instanceof Array) { newObj[newKey] = (function() { var _i, _len, _results; _results = []; for (_i = 0, _len = value.length; _i < _len; _i++) { item = value[_i]; _results.push(typeof item === 'object' ? Util.convertObjectKeysToUnderscores(item) : item); } return _results; })(); } else if (typeof value === 'object') { if (value instanceof Date || value === null) { newObj[newKey] = value; } else { newObj[newKey] = Util.convertObjectKeysToUnderscores(value); } } else { newObj[newKey] = value; } } return newObj; }; Util.convertNodeToObject = function(obj) {
newArray = []; for (key in obj) { value = obj[key]; if (key !== '@') { if (value instanceof Array) { for (_i = 0, _len = value.length; _i < _len; _i++) { item = value[_i]; newArray.push(this.convertNodeToObject(item)); } } else { newArray.push(this.convertNodeToObject(value)); } } } return newArray; } else if (obj['@'].type === 'collection') { newObj = {}; for (key in obj) { value = obj[key]; if (key !== '@') { newObj[this.toCamelCase(key)] = this.convertNodeToObject(value); } } return newObj; } else if (obj['@'].nil === 'true') { return null; } else if (obj['@'].type === 'integer') { return parseInt(obj['#']); } else if (obj['@'].type === 'boolean') { return obj['#'] === 'true'; } else { return obj['#']; } } else if (obj instanceof Array) { _results = []; for (_j = 0, _len1 = obj.length; _j < _len1; _j++) { item = obj[_j]; _results.push(this.convertNodeToObject(item)); } return _results; } else if (typeof obj === 'object' && this.objectIsEmpty(obj)) { return ''; } else if (typeof obj === 'object') { newObj = {}; for (key in obj) { value = obj[key]; newObj[this.toCamelCase(key)] = this.convertNodeToObject(value); } return newObj; } else { return obj; } }; Util.objectIsEmpty = function(obj) { var key, value; for (key in obj) { value = obj[key]; return false; } return true; }; Util.arrayIsEmpty = function(array) { if (!(array instanceof Array)) { return false; } if (array.length > 0) { return false; } return true; }; Util.toCamelCase = function(string) { return string.replace(/([\-\_][a-z0-9])/g, function(match) { return match.toUpperCase().replace('-', '').replace('_', ''); }); }; Util.toUnderscore = function(string) { return string.replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2').replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase(); }; Util.flatten = function(array) { var _this = this; while (this._containsArray(array)) { array = array.reduce(function(first, rest) { first = first instanceof Array ? first : [first]; rest = rest instanceof Array ? _this.flatten(rest) : rest; return first.concat(rest); }); } return array; }; Util.merge = function(obj1, obj2) { var key, value; for (key in obj2) { value = obj2[key]; obj1[key] = value; } return obj1; }; Util.without = function(array1, array2) { var newArray, value, _i, _len; newArray = []; for (_i = 0, _len = array1.length; _i < _len; _i++) { value = array1[_i]; if (!this._containsValue(array2, value)) { newArray.push(value); } } return newArray; }; Util.supportsStreams2 = function() { return semver.satisfies(process.version, '>=0.10'); }; Util._containsValue = function(array, element) { return array.indexOf(element) !== -1; }; Util._containsArray = function(array) { var element, _i, _len; for (_i = 0, _len = array.length; _i < _len; _i++) { element = array[_i]; if (element instanceof Array) { return true; } } }; return Util; })(); exports.Util = Util;
var item, key, newArray, newObj, value, _i, _j, _len, _len1, _results; if (typeof obj === 'object' && obj['@']) { if (obj['@'].type === 'array') {
random_line_split
util.js
//@ sourceMappingURL=util.map // Generated by CoffeeScript 1.6.1 var Util, semver; semver = require('semver'); Util = (function() { function Util() {} Util.convertObjectKeysToUnderscores = function(obj) { var item, key, newKey, newObj, value; newObj = {}; for (key in obj) { value = obj[key]; newKey = Util.toUnderscore(key); if (value instanceof Array) { newObj[newKey] = (function() { var _i, _len, _results; _results = []; for (_i = 0, _len = value.length; _i < _len; _i++) { item = value[_i]; _results.push(typeof item === 'object' ? Util.convertObjectKeysToUnderscores(item) : item); } return _results; })(); } else if (typeof value === 'object') { if (value instanceof Date || value === null) { newObj[newKey] = value; } else { newObj[newKey] = Util.convertObjectKeysToUnderscores(value); } } else { newObj[newKey] = value; } } return newObj; }; Util.convertNodeToObject = function(obj) { var item, key, newArray, newObj, value, _i, _j, _len, _len1, _results; if (typeof obj === 'object' && obj['@']) { if (obj['@'].type === 'array') { newArray = []; for (key in obj) { value = obj[key]; if (key !== '@') { if (value instanceof Array) { for (_i = 0, _len = value.length; _i < _len; _i++) { item = value[_i]; newArray.push(this.convertNodeToObject(item)); } } else { newArray.push(this.convertNodeToObject(value)); } } } return newArray; } else if (obj['@'].type === 'collection') { newObj = {}; for (key in obj) { value = obj[key]; if (key !== '@') { newObj[this.toCamelCase(key)] = this.convertNodeToObject(value); } } return newObj; } else if (obj['@'].nil === 'true') { return null; } else if (obj['@'].type === 'integer')
else if (obj['@'].type === 'boolean') { return obj['#'] === 'true'; } else { return obj['#']; } } else if (obj instanceof Array) { _results = []; for (_j = 0, _len1 = obj.length; _j < _len1; _j++) { item = obj[_j]; _results.push(this.convertNodeToObject(item)); } return _results; } else if (typeof obj === 'object' && this.objectIsEmpty(obj)) { return ''; } else if (typeof obj === 'object') { newObj = {}; for (key in obj) { value = obj[key]; newObj[this.toCamelCase(key)] = this.convertNodeToObject(value); } return newObj; } else { return obj; } }; Util.objectIsEmpty = function(obj) { var key, value; for (key in obj) { value = obj[key]; return false; } return true; }; Util.arrayIsEmpty = function(array) { if (!(array instanceof Array)) { return false; } if (array.length > 0) { return false; } return true; }; Util.toCamelCase = function(string) { return string.replace(/([\-\_][a-z0-9])/g, function(match) { return match.toUpperCase().replace('-', '').replace('_', ''); }); }; Util.toUnderscore = function(string) { return string.replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2').replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase(); }; Util.flatten = function(array) { var _this = this; while (this._containsArray(array)) { array = array.reduce(function(first, rest) { first = first instanceof Array ? first : [first]; rest = rest instanceof Array ? _this.flatten(rest) : rest; return first.concat(rest); }); } return array; }; Util.merge = function(obj1, obj2) { var key, value; for (key in obj2) { value = obj2[key]; obj1[key] = value; } return obj1; }; Util.without = function(array1, array2) { var newArray, value, _i, _len; newArray = []; for (_i = 0, _len = array1.length; _i < _len; _i++) { value = array1[_i]; if (!this._containsValue(array2, value)) { newArray.push(value); } } return newArray; }; Util.supportsStreams2 = function() { return semver.satisfies(process.version, '>=0.10'); }; Util._containsValue = function(array, element) { return array.indexOf(element) !== -1; }; Util._containsArray = function(array) { var element, _i, _len; for (_i = 0, _len = array.length; _i < _len; _i++) { element = array[_i]; if (element instanceof Array) { return true; } } }; return Util; })(); exports.Util = Util;
{ return parseInt(obj['#']); }
conditional_block
util.js
//@ sourceMappingURL=util.map // Generated by CoffeeScript 1.6.1 var Util, semver; semver = require('semver'); Util = (function() { function
() {} Util.convertObjectKeysToUnderscores = function(obj) { var item, key, newKey, newObj, value; newObj = {}; for (key in obj) { value = obj[key]; newKey = Util.toUnderscore(key); if (value instanceof Array) { newObj[newKey] = (function() { var _i, _len, _results; _results = []; for (_i = 0, _len = value.length; _i < _len; _i++) { item = value[_i]; _results.push(typeof item === 'object' ? Util.convertObjectKeysToUnderscores(item) : item); } return _results; })(); } else if (typeof value === 'object') { if (value instanceof Date || value === null) { newObj[newKey] = value; } else { newObj[newKey] = Util.convertObjectKeysToUnderscores(value); } } else { newObj[newKey] = value; } } return newObj; }; Util.convertNodeToObject = function(obj) { var item, key, newArray, newObj, value, _i, _j, _len, _len1, _results; if (typeof obj === 'object' && obj['@']) { if (obj['@'].type === 'array') { newArray = []; for (key in obj) { value = obj[key]; if (key !== '@') { if (value instanceof Array) { for (_i = 0, _len = value.length; _i < _len; _i++) { item = value[_i]; newArray.push(this.convertNodeToObject(item)); } } else { newArray.push(this.convertNodeToObject(value)); } } } return newArray; } else if (obj['@'].type === 'collection') { newObj = {}; for (key in obj) { value = obj[key]; if (key !== '@') { newObj[this.toCamelCase(key)] = this.convertNodeToObject(value); } } return newObj; } else if (obj['@'].nil === 'true') { return null; } else if (obj['@'].type === 'integer') { return parseInt(obj['#']); } else if (obj['@'].type === 'boolean') { return obj['#'] === 'true'; } else { return obj['#']; } } else if (obj instanceof Array) { _results = []; for (_j = 0, _len1 = obj.length; _j < _len1; _j++) { item = obj[_j]; _results.push(this.convertNodeToObject(item)); } return _results; } else if (typeof obj === 'object' && this.objectIsEmpty(obj)) { return ''; } else if (typeof obj === 'object') { newObj = {}; for (key in obj) { value = obj[key]; newObj[this.toCamelCase(key)] = this.convertNodeToObject(value); } return newObj; } else { return obj; } }; Util.objectIsEmpty = function(obj) { var key, value; for (key in obj) { value = obj[key]; return false; } return true; }; Util.arrayIsEmpty = function(array) { if (!(array instanceof Array)) { return false; } if (array.length > 0) { return false; } return true; }; Util.toCamelCase = function(string) { return string.replace(/([\-\_][a-z0-9])/g, function(match) { return match.toUpperCase().replace('-', '').replace('_', ''); }); }; Util.toUnderscore = function(string) { return string.replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2').replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase(); }; Util.flatten = function(array) { var _this = this; while (this._containsArray(array)) { array = array.reduce(function(first, rest) { first = first instanceof Array ? first : [first]; rest = rest instanceof Array ? _this.flatten(rest) : rest; return first.concat(rest); }); } return array; }; Util.merge = function(obj1, obj2) { var key, value; for (key in obj2) { value = obj2[key]; obj1[key] = value; } return obj1; }; Util.without = function(array1, array2) { var newArray, value, _i, _len; newArray = []; for (_i = 0, _len = array1.length; _i < _len; _i++) { value = array1[_i]; if (!this._containsValue(array2, value)) { newArray.push(value); } } return newArray; }; Util.supportsStreams2 = function() { return semver.satisfies(process.version, '>=0.10'); }; Util._containsValue = function(array, element) { return array.indexOf(element) !== -1; }; Util._containsArray = function(array) { var element, _i, _len; for (_i = 0, _len = array.length; _i < _len; _i++) { element = array[_i]; if (element instanceof Array) { return true; } } }; return Util; })(); exports.Util = Util;
Util
identifier_name
util.js
//@ sourceMappingURL=util.map // Generated by CoffeeScript 1.6.1 var Util, semver; semver = require('semver'); Util = (function() { function Util()
Util.convertObjectKeysToUnderscores = function(obj) { var item, key, newKey, newObj, value; newObj = {}; for (key in obj) { value = obj[key]; newKey = Util.toUnderscore(key); if (value instanceof Array) { newObj[newKey] = (function() { var _i, _len, _results; _results = []; for (_i = 0, _len = value.length; _i < _len; _i++) { item = value[_i]; _results.push(typeof item === 'object' ? Util.convertObjectKeysToUnderscores(item) : item); } return _results; })(); } else if (typeof value === 'object') { if (value instanceof Date || value === null) { newObj[newKey] = value; } else { newObj[newKey] = Util.convertObjectKeysToUnderscores(value); } } else { newObj[newKey] = value; } } return newObj; }; Util.convertNodeToObject = function(obj) { var item, key, newArray, newObj, value, _i, _j, _len, _len1, _results; if (typeof obj === 'object' && obj['@']) { if (obj['@'].type === 'array') { newArray = []; for (key in obj) { value = obj[key]; if (key !== '@') { if (value instanceof Array) { for (_i = 0, _len = value.length; _i < _len; _i++) { item = value[_i]; newArray.push(this.convertNodeToObject(item)); } } else { newArray.push(this.convertNodeToObject(value)); } } } return newArray; } else if (obj['@'].type === 'collection') { newObj = {}; for (key in obj) { value = obj[key]; if (key !== '@') { newObj[this.toCamelCase(key)] = this.convertNodeToObject(value); } } return newObj; } else if (obj['@'].nil === 'true') { return null; } else if (obj['@'].type === 'integer') { return parseInt(obj['#']); } else if (obj['@'].type === 'boolean') { return obj['#'] === 'true'; } else { return obj['#']; } } else if (obj instanceof Array) { _results = []; for (_j = 0, _len1 = obj.length; _j < _len1; _j++) { item = obj[_j]; _results.push(this.convertNodeToObject(item)); } return _results; } else if (typeof obj === 'object' && this.objectIsEmpty(obj)) { return ''; } else if (typeof obj === 'object') { newObj = {}; for (key in obj) { value = obj[key]; newObj[this.toCamelCase(key)] = this.convertNodeToObject(value); } return newObj; } else { return obj; } }; Util.objectIsEmpty = function(obj) { var key, value; for (key in obj) { value = obj[key]; return false; } return true; }; Util.arrayIsEmpty = function(array) { if (!(array instanceof Array)) { return false; } if (array.length > 0) { return false; } return true; }; Util.toCamelCase = function(string) { return string.replace(/([\-\_][a-z0-9])/g, function(match) { return match.toUpperCase().replace('-', '').replace('_', ''); }); }; Util.toUnderscore = function(string) { return string.replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2').replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase(); }; Util.flatten = function(array) { var _this = this; while (this._containsArray(array)) { array = array.reduce(function(first, rest) { first = first instanceof Array ? first : [first]; rest = rest instanceof Array ? _this.flatten(rest) : rest; return first.concat(rest); }); } return array; }; Util.merge = function(obj1, obj2) { var key, value; for (key in obj2) { value = obj2[key]; obj1[key] = value; } return obj1; }; Util.without = function(array1, array2) { var newArray, value, _i, _len; newArray = []; for (_i = 0, _len = array1.length; _i < _len; _i++) { value = array1[_i]; if (!this._containsValue(array2, value)) { newArray.push(value); } } return newArray; }; Util.supportsStreams2 = function() { return semver.satisfies(process.version, '>=0.10'); }; Util._containsValue = function(array, element) { return array.indexOf(element) !== -1; }; Util._containsArray = function(array) { var element, _i, _len; for (_i = 0, _len = array.length; _i < _len; _i++) { element = array[_i]; if (element instanceof Array) { return true; } } }; return Util; })(); exports.Util = Util;
{}
identifier_body
reseeding.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! A wrapper around another RNG that reseeds it after it //! generates a certain number of random bytes. use core::prelude::*; use {Rng, SeedableRng}; /// How many bytes of entropy the underling RNG is allowed to generate /// before it is reseeded. const DEFAULT_GENERATION_THRESHOLD: usize = 32 * 1024; /// A wrapper around any RNG which reseeds the underlying RNG after it /// has generated a certain number of random bytes. pub struct ReseedingRng<R, Rsdr> { rng: R, generation_threshold: usize, bytes_generated: usize, /// Controls the behaviour when reseeding the RNG. pub reseeder: Rsdr, } impl<R: Rng, Rsdr: Reseeder<R>> ReseedingRng<R, Rsdr> { /// Create a new `ReseedingRng` with the given parameters. /// /// # Arguments /// /// * `rng`: the random number generator to use. /// * `generation_threshold`: the number of bytes of entropy at which to reseed the RNG. /// * `reseeder`: the reseeding object to use. pub fn new(rng: R, generation_threshold: usize, reseeder: Rsdr) -> ReseedingRng<R,Rsdr>
/// Reseed the internal RNG if the number of bytes that have been /// generated exceed the threshold. pub fn reseed_if_necessary(&mut self) { if self.bytes_generated >= self.generation_threshold { self.reseeder.reseed(&mut self.rng); self.bytes_generated = 0; } } } impl<R: Rng, Rsdr: Reseeder<R>> Rng for ReseedingRng<R, Rsdr> { fn next_u32(&mut self) -> u32 { self.reseed_if_necessary(); self.bytes_generated += 4; self.rng.next_u32() } fn next_u64(&mut self) -> u64 { self.reseed_if_necessary(); self.bytes_generated += 8; self.rng.next_u64() } fn fill_bytes(&mut self, dest: &mut [u8]) { self.reseed_if_necessary(); self.bytes_generated += dest.len(); self.rng.fill_bytes(dest) } } impl<S, R: SeedableRng<S>, Rsdr: Reseeder<R> + Default> SeedableRng<(Rsdr, S)> for ReseedingRng<R, Rsdr> { fn reseed(&mut self, (rsdr, seed): (Rsdr, S)) { self.rng.reseed(seed); self.reseeder = rsdr; self.bytes_generated = 0; } /// Create a new `ReseedingRng` from the given reseeder and /// seed. This uses a default value for `generation_threshold`. fn from_seed((rsdr, seed): (Rsdr, S)) -> ReseedingRng<R, Rsdr> { ReseedingRng { rng: SeedableRng::from_seed(seed), generation_threshold: DEFAULT_GENERATION_THRESHOLD, bytes_generated: 0, reseeder: rsdr } } } /// Something that can be used to reseed an RNG via `ReseedingRng`. pub trait Reseeder<R> { /// Reseed the given RNG. fn reseed(&mut self, rng: &mut R); } /// Reseed an RNG using a `Default` instance. This reseeds by /// replacing the RNG with the result of a `Default::default` call. #[derive(Copy, Clone)] pub struct ReseedWithDefault; impl<R: Rng + Default> Reseeder<R> for ReseedWithDefault { fn reseed(&mut self, rng: &mut R) { *rng = Default::default(); } } #[stable(feature = "rust1", since = "1.0.0")] impl Default for ReseedWithDefault { #[stable(feature = "rust1", since = "1.0.0")] fn default() -> ReseedWithDefault { ReseedWithDefault } } #[cfg(test)] mod tests { use std::prelude::v1::*; use core::iter::{order, repeat}; use super::{ReseedingRng, ReseedWithDefault}; use {SeedableRng, Rng}; struct Counter { i: u32 } impl Rng for Counter { fn next_u32(&mut self) -> u32 { self.i += 1; // very random self.i - 1 } } impl Default for Counter { fn default() -> Counter { Counter { i: 0 } } } impl SeedableRng<u32> for Counter { fn reseed(&mut self, seed: u32) { self.i = seed; } fn from_seed(seed: u32) -> Counter { Counter { i: seed } } } type MyRng = ReseedingRng<Counter, ReseedWithDefault>; #[test] fn test_reseeding() { let mut rs = ReseedingRng::new(Counter {i:0}, 400, ReseedWithDefault); let mut i = 0; for _ in 0..1000 { assert_eq!(rs.next_u32(), i % 100); i += 1; } } #[test] fn test_rng_seeded() { let mut ra: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2)); let mut rb: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2)); assert!(order::equals(ra.gen_ascii_chars().take(100), rb.gen_ascii_chars().take(100))); } #[test] fn test_rng_reseed() { let mut r: MyRng = SeedableRng::from_seed((ReseedWithDefault, 3)); let string1: String = r.gen_ascii_chars().take(100).collect(); r.reseed((ReseedWithDefault, 3)); let string2: String = r.gen_ascii_chars().take(100).collect(); assert_eq!(string1, string2); } const FILL_BYTES_V_LEN: usize = 13579; #[test] fn test_rng_fill_bytes() { let mut v = vec![0; FILL_BYTES_V_LEN]; ::test::rng().fill_bytes(&mut v); // Sanity test: if we've gotten here, `fill_bytes` has not infinitely // recursed. assert_eq!(v.len(), FILL_BYTES_V_LEN); // To test that `fill_bytes` actually did something, check that the // average of `v` is not 0. let mut sum = 0.0; for &x in &v { sum += x as f64; } assert!(sum / v.len() as f64 != 0.0); } }
{ ReseedingRng { rng: rng, generation_threshold: generation_threshold, bytes_generated: 0, reseeder: reseeder } }
identifier_body
reseeding.rs
// 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. //! A wrapper around another RNG that reseeds it after it //! generates a certain number of random bytes. use core::prelude::*; use {Rng, SeedableRng}; /// How many bytes of entropy the underling RNG is allowed to generate /// before it is reseeded. const DEFAULT_GENERATION_THRESHOLD: usize = 32 * 1024; /// A wrapper around any RNG which reseeds the underlying RNG after it /// has generated a certain number of random bytes. pub struct ReseedingRng<R, Rsdr> { rng: R, generation_threshold: usize, bytes_generated: usize, /// Controls the behaviour when reseeding the RNG. pub reseeder: Rsdr, } impl<R: Rng, Rsdr: Reseeder<R>> ReseedingRng<R, Rsdr> { /// Create a new `ReseedingRng` with the given parameters. /// /// # Arguments /// /// * `rng`: the random number generator to use. /// * `generation_threshold`: the number of bytes of entropy at which to reseed the RNG. /// * `reseeder`: the reseeding object to use. pub fn new(rng: R, generation_threshold: usize, reseeder: Rsdr) -> ReseedingRng<R,Rsdr> { ReseedingRng { rng: rng, generation_threshold: generation_threshold, bytes_generated: 0, reseeder: reseeder } } /// Reseed the internal RNG if the number of bytes that have been /// generated exceed the threshold. pub fn reseed_if_necessary(&mut self) { if self.bytes_generated >= self.generation_threshold { self.reseeder.reseed(&mut self.rng); self.bytes_generated = 0; } } } impl<R: Rng, Rsdr: Reseeder<R>> Rng for ReseedingRng<R, Rsdr> { fn next_u32(&mut self) -> u32 { self.reseed_if_necessary(); self.bytes_generated += 4; self.rng.next_u32() } fn next_u64(&mut self) -> u64 { self.reseed_if_necessary(); self.bytes_generated += 8; self.rng.next_u64() } fn fill_bytes(&mut self, dest: &mut [u8]) { self.reseed_if_necessary(); self.bytes_generated += dest.len(); self.rng.fill_bytes(dest) } } impl<S, R: SeedableRng<S>, Rsdr: Reseeder<R> + Default> SeedableRng<(Rsdr, S)> for ReseedingRng<R, Rsdr> { fn reseed(&mut self, (rsdr, seed): (Rsdr, S)) { self.rng.reseed(seed); self.reseeder = rsdr; self.bytes_generated = 0; } /// Create a new `ReseedingRng` from the given reseeder and /// seed. This uses a default value for `generation_threshold`. fn from_seed((rsdr, seed): (Rsdr, S)) -> ReseedingRng<R, Rsdr> { ReseedingRng { rng: SeedableRng::from_seed(seed), generation_threshold: DEFAULT_GENERATION_THRESHOLD, bytes_generated: 0, reseeder: rsdr } } } /// Something that can be used to reseed an RNG via `ReseedingRng`. pub trait Reseeder<R> { /// Reseed the given RNG. fn reseed(&mut self, rng: &mut R); } /// Reseed an RNG using a `Default` instance. This reseeds by /// replacing the RNG with the result of a `Default::default` call. #[derive(Copy, Clone)] pub struct ReseedWithDefault; impl<R: Rng + Default> Reseeder<R> for ReseedWithDefault { fn reseed(&mut self, rng: &mut R) { *rng = Default::default(); } } #[stable(feature = "rust1", since = "1.0.0")] impl Default for ReseedWithDefault { #[stable(feature = "rust1", since = "1.0.0")] fn default() -> ReseedWithDefault { ReseedWithDefault } } #[cfg(test)] mod tests { use std::prelude::v1::*; use core::iter::{order, repeat}; use super::{ReseedingRng, ReseedWithDefault}; use {SeedableRng, Rng}; struct Counter { i: u32 } impl Rng for Counter { fn next_u32(&mut self) -> u32 { self.i += 1; // very random self.i - 1 } } impl Default for Counter { fn default() -> Counter { Counter { i: 0 } } } impl SeedableRng<u32> for Counter { fn reseed(&mut self, seed: u32) { self.i = seed; } fn from_seed(seed: u32) -> Counter { Counter { i: seed } } } type MyRng = ReseedingRng<Counter, ReseedWithDefault>; #[test] fn test_reseeding() { let mut rs = ReseedingRng::new(Counter {i:0}, 400, ReseedWithDefault); let mut i = 0; for _ in 0..1000 { assert_eq!(rs.next_u32(), i % 100); i += 1; } } #[test] fn test_rng_seeded() { let mut ra: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2)); let mut rb: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2)); assert!(order::equals(ra.gen_ascii_chars().take(100), rb.gen_ascii_chars().take(100))); } #[test] fn test_rng_reseed() { let mut r: MyRng = SeedableRng::from_seed((ReseedWithDefault, 3)); let string1: String = r.gen_ascii_chars().take(100).collect(); r.reseed((ReseedWithDefault, 3)); let string2: String = r.gen_ascii_chars().take(100).collect(); assert_eq!(string1, string2); } const FILL_BYTES_V_LEN: usize = 13579; #[test] fn test_rng_fill_bytes() { let mut v = vec![0; FILL_BYTES_V_LEN]; ::test::rng().fill_bytes(&mut v); // Sanity test: if we've gotten here, `fill_bytes` has not infinitely // recursed. assert_eq!(v.len(), FILL_BYTES_V_LEN); // To test that `fill_bytes` actually did something, check that the // average of `v` is not 0. let mut sum = 0.0; for &x in &v { sum += x as f64; } assert!(sum / v.len() as f64 != 0.0); } }
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. //
random_line_split
reseeding.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! A wrapper around another RNG that reseeds it after it //! generates a certain number of random bytes. use core::prelude::*; use {Rng, SeedableRng}; /// How many bytes of entropy the underling RNG is allowed to generate /// before it is reseeded. const DEFAULT_GENERATION_THRESHOLD: usize = 32 * 1024; /// A wrapper around any RNG which reseeds the underlying RNG after it /// has generated a certain number of random bytes. pub struct ReseedingRng<R, Rsdr> { rng: R, generation_threshold: usize, bytes_generated: usize, /// Controls the behaviour when reseeding the RNG. pub reseeder: Rsdr, } impl<R: Rng, Rsdr: Reseeder<R>> ReseedingRng<R, Rsdr> { /// Create a new `ReseedingRng` with the given parameters. /// /// # Arguments /// /// * `rng`: the random number generator to use. /// * `generation_threshold`: the number of bytes of entropy at which to reseed the RNG. /// * `reseeder`: the reseeding object to use. pub fn new(rng: R, generation_threshold: usize, reseeder: Rsdr) -> ReseedingRng<R,Rsdr> { ReseedingRng { rng: rng, generation_threshold: generation_threshold, bytes_generated: 0, reseeder: reseeder } } /// Reseed the internal RNG if the number of bytes that have been /// generated exceed the threshold. pub fn reseed_if_necessary(&mut self) { if self.bytes_generated >= self.generation_threshold
} } impl<R: Rng, Rsdr: Reseeder<R>> Rng for ReseedingRng<R, Rsdr> { fn next_u32(&mut self) -> u32 { self.reseed_if_necessary(); self.bytes_generated += 4; self.rng.next_u32() } fn next_u64(&mut self) -> u64 { self.reseed_if_necessary(); self.bytes_generated += 8; self.rng.next_u64() } fn fill_bytes(&mut self, dest: &mut [u8]) { self.reseed_if_necessary(); self.bytes_generated += dest.len(); self.rng.fill_bytes(dest) } } impl<S, R: SeedableRng<S>, Rsdr: Reseeder<R> + Default> SeedableRng<(Rsdr, S)> for ReseedingRng<R, Rsdr> { fn reseed(&mut self, (rsdr, seed): (Rsdr, S)) { self.rng.reseed(seed); self.reseeder = rsdr; self.bytes_generated = 0; } /// Create a new `ReseedingRng` from the given reseeder and /// seed. This uses a default value for `generation_threshold`. fn from_seed((rsdr, seed): (Rsdr, S)) -> ReseedingRng<R, Rsdr> { ReseedingRng { rng: SeedableRng::from_seed(seed), generation_threshold: DEFAULT_GENERATION_THRESHOLD, bytes_generated: 0, reseeder: rsdr } } } /// Something that can be used to reseed an RNG via `ReseedingRng`. pub trait Reseeder<R> { /// Reseed the given RNG. fn reseed(&mut self, rng: &mut R); } /// Reseed an RNG using a `Default` instance. This reseeds by /// replacing the RNG with the result of a `Default::default` call. #[derive(Copy, Clone)] pub struct ReseedWithDefault; impl<R: Rng + Default> Reseeder<R> for ReseedWithDefault { fn reseed(&mut self, rng: &mut R) { *rng = Default::default(); } } #[stable(feature = "rust1", since = "1.0.0")] impl Default for ReseedWithDefault { #[stable(feature = "rust1", since = "1.0.0")] fn default() -> ReseedWithDefault { ReseedWithDefault } } #[cfg(test)] mod tests { use std::prelude::v1::*; use core::iter::{order, repeat}; use super::{ReseedingRng, ReseedWithDefault}; use {SeedableRng, Rng}; struct Counter { i: u32 } impl Rng for Counter { fn next_u32(&mut self) -> u32 { self.i += 1; // very random self.i - 1 } } impl Default for Counter { fn default() -> Counter { Counter { i: 0 } } } impl SeedableRng<u32> for Counter { fn reseed(&mut self, seed: u32) { self.i = seed; } fn from_seed(seed: u32) -> Counter { Counter { i: seed } } } type MyRng = ReseedingRng<Counter, ReseedWithDefault>; #[test] fn test_reseeding() { let mut rs = ReseedingRng::new(Counter {i:0}, 400, ReseedWithDefault); let mut i = 0; for _ in 0..1000 { assert_eq!(rs.next_u32(), i % 100); i += 1; } } #[test] fn test_rng_seeded() { let mut ra: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2)); let mut rb: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2)); assert!(order::equals(ra.gen_ascii_chars().take(100), rb.gen_ascii_chars().take(100))); } #[test] fn test_rng_reseed() { let mut r: MyRng = SeedableRng::from_seed((ReseedWithDefault, 3)); let string1: String = r.gen_ascii_chars().take(100).collect(); r.reseed((ReseedWithDefault, 3)); let string2: String = r.gen_ascii_chars().take(100).collect(); assert_eq!(string1, string2); } const FILL_BYTES_V_LEN: usize = 13579; #[test] fn test_rng_fill_bytes() { let mut v = vec![0; FILL_BYTES_V_LEN]; ::test::rng().fill_bytes(&mut v); // Sanity test: if we've gotten here, `fill_bytes` has not infinitely // recursed. assert_eq!(v.len(), FILL_BYTES_V_LEN); // To test that `fill_bytes` actually did something, check that the // average of `v` is not 0. let mut sum = 0.0; for &x in &v { sum += x as f64; } assert!(sum / v.len() as f64 != 0.0); } }
{ self.reseeder.reseed(&mut self.rng); self.bytes_generated = 0; }
conditional_block
reseeding.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! A wrapper around another RNG that reseeds it after it //! generates a certain number of random bytes. use core::prelude::*; use {Rng, SeedableRng}; /// How many bytes of entropy the underling RNG is allowed to generate /// before it is reseeded. const DEFAULT_GENERATION_THRESHOLD: usize = 32 * 1024; /// A wrapper around any RNG which reseeds the underlying RNG after it /// has generated a certain number of random bytes. pub struct
<R, Rsdr> { rng: R, generation_threshold: usize, bytes_generated: usize, /// Controls the behaviour when reseeding the RNG. pub reseeder: Rsdr, } impl<R: Rng, Rsdr: Reseeder<R>> ReseedingRng<R, Rsdr> { /// Create a new `ReseedingRng` with the given parameters. /// /// # Arguments /// /// * `rng`: the random number generator to use. /// * `generation_threshold`: the number of bytes of entropy at which to reseed the RNG. /// * `reseeder`: the reseeding object to use. pub fn new(rng: R, generation_threshold: usize, reseeder: Rsdr) -> ReseedingRng<R,Rsdr> { ReseedingRng { rng: rng, generation_threshold: generation_threshold, bytes_generated: 0, reseeder: reseeder } } /// Reseed the internal RNG if the number of bytes that have been /// generated exceed the threshold. pub fn reseed_if_necessary(&mut self) { if self.bytes_generated >= self.generation_threshold { self.reseeder.reseed(&mut self.rng); self.bytes_generated = 0; } } } impl<R: Rng, Rsdr: Reseeder<R>> Rng for ReseedingRng<R, Rsdr> { fn next_u32(&mut self) -> u32 { self.reseed_if_necessary(); self.bytes_generated += 4; self.rng.next_u32() } fn next_u64(&mut self) -> u64 { self.reseed_if_necessary(); self.bytes_generated += 8; self.rng.next_u64() } fn fill_bytes(&mut self, dest: &mut [u8]) { self.reseed_if_necessary(); self.bytes_generated += dest.len(); self.rng.fill_bytes(dest) } } impl<S, R: SeedableRng<S>, Rsdr: Reseeder<R> + Default> SeedableRng<(Rsdr, S)> for ReseedingRng<R, Rsdr> { fn reseed(&mut self, (rsdr, seed): (Rsdr, S)) { self.rng.reseed(seed); self.reseeder = rsdr; self.bytes_generated = 0; } /// Create a new `ReseedingRng` from the given reseeder and /// seed. This uses a default value for `generation_threshold`. fn from_seed((rsdr, seed): (Rsdr, S)) -> ReseedingRng<R, Rsdr> { ReseedingRng { rng: SeedableRng::from_seed(seed), generation_threshold: DEFAULT_GENERATION_THRESHOLD, bytes_generated: 0, reseeder: rsdr } } } /// Something that can be used to reseed an RNG via `ReseedingRng`. pub trait Reseeder<R> { /// Reseed the given RNG. fn reseed(&mut self, rng: &mut R); } /// Reseed an RNG using a `Default` instance. This reseeds by /// replacing the RNG with the result of a `Default::default` call. #[derive(Copy, Clone)] pub struct ReseedWithDefault; impl<R: Rng + Default> Reseeder<R> for ReseedWithDefault { fn reseed(&mut self, rng: &mut R) { *rng = Default::default(); } } #[stable(feature = "rust1", since = "1.0.0")] impl Default for ReseedWithDefault { #[stable(feature = "rust1", since = "1.0.0")] fn default() -> ReseedWithDefault { ReseedWithDefault } } #[cfg(test)] mod tests { use std::prelude::v1::*; use core::iter::{order, repeat}; use super::{ReseedingRng, ReseedWithDefault}; use {SeedableRng, Rng}; struct Counter { i: u32 } impl Rng for Counter { fn next_u32(&mut self) -> u32 { self.i += 1; // very random self.i - 1 } } impl Default for Counter { fn default() -> Counter { Counter { i: 0 } } } impl SeedableRng<u32> for Counter { fn reseed(&mut self, seed: u32) { self.i = seed; } fn from_seed(seed: u32) -> Counter { Counter { i: seed } } } type MyRng = ReseedingRng<Counter, ReseedWithDefault>; #[test] fn test_reseeding() { let mut rs = ReseedingRng::new(Counter {i:0}, 400, ReseedWithDefault); let mut i = 0; for _ in 0..1000 { assert_eq!(rs.next_u32(), i % 100); i += 1; } } #[test] fn test_rng_seeded() { let mut ra: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2)); let mut rb: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2)); assert!(order::equals(ra.gen_ascii_chars().take(100), rb.gen_ascii_chars().take(100))); } #[test] fn test_rng_reseed() { let mut r: MyRng = SeedableRng::from_seed((ReseedWithDefault, 3)); let string1: String = r.gen_ascii_chars().take(100).collect(); r.reseed((ReseedWithDefault, 3)); let string2: String = r.gen_ascii_chars().take(100).collect(); assert_eq!(string1, string2); } const FILL_BYTES_V_LEN: usize = 13579; #[test] fn test_rng_fill_bytes() { let mut v = vec![0; FILL_BYTES_V_LEN]; ::test::rng().fill_bytes(&mut v); // Sanity test: if we've gotten here, `fill_bytes` has not infinitely // recursed. assert_eq!(v.len(), FILL_BYTES_V_LEN); // To test that `fill_bytes` actually did something, check that the // average of `v` is not 0. let mut sum = 0.0; for &x in &v { sum += x as f64; } assert!(sum / v.len() as f64 != 0.0); } }
ReseedingRng
identifier_name
error.rs
use std::error::Error as StdError; use std::string; use std::{fmt, io}; /// The errors that can arise while parsing a JSON stream. #[derive(Clone, Copy, PartialEq)] pub enum ErrorCode { InvalidSyntax, InvalidNumber, EOFWhileParsingObject, EOFWhileParsingArray, EOFWhileParsingValue, EOFWhileParsingString, KeyMustBeAString, ExpectedColon, TrailingCharacters, TrailingComma, InvalidEscape, InvalidUnicodeCodePoint, LoneLeadingSurrogateInHexEscape, UnexpectedEndOfHexEscape, UnrecognizedHex, NotFourDigit, ControlCharacterInString, NotUtf8, } #[derive(Debug)] pub enum ParserError { /// msg, line, col SyntaxError(ErrorCode, usize, usize), IoError(io::Error), } impl PartialEq for ParserError { fn eq(&self, other: &ParserError) -> bool { match (self, other) { (&ParserError::SyntaxError(msg0, line0, col0), &ParserError::SyntaxError(msg1, line1, col1)) => msg0 == msg1 && line0 == line1 && col0 == col1, (&ParserError::IoError(_), _) => false, (_, &ParserError::IoError(_)) => false, } } } /// Returns a readable error string for a given error code. pub fn error_str(error: ErrorCode) -> &'static str { match error { ErrorCode::InvalidSyntax => "invalid syntax", ErrorCode::InvalidNumber => "invalid number", ErrorCode::EOFWhileParsingObject => "EOF While parsing object", ErrorCode::EOFWhileParsingArray => "EOF While parsing array", ErrorCode::EOFWhileParsingValue => "EOF While parsing value", ErrorCode::EOFWhileParsingString => "EOF While parsing string", ErrorCode::KeyMustBeAString => "key must be a string", ErrorCode::ExpectedColon => "expected `:`", ErrorCode::TrailingCharacters => "trailing characters", ErrorCode::TrailingComma => "trailing comma", ErrorCode::InvalidEscape => "invalid escape", ErrorCode::UnrecognizedHex => "invalid \\u{ esc}ape (unrecognized hex)", ErrorCode::NotFourDigit => "invalid \\u{ esc}ape (not four digits)", ErrorCode::ControlCharacterInString => "unescaped control character in string", ErrorCode::NotUtf8 => "contents not utf-8", ErrorCode::InvalidUnicodeCodePoint => "invalid Unicode code point", ErrorCode::LoneLeadingSurrogateInHexEscape => "lone leading surrogate in hex escape", ErrorCode::UnexpectedEndOfHexEscape => "unexpected end of hex escape", } } #[derive(PartialEq, Debug)] pub enum DecoderError { ParseError(ParserError), ExpectedError(string::String, string::String), MissingFieldError(string::String), UnknownVariantError(string::String), ApplicationError(string::String), EOF, } #[derive(Copy, Debug)] pub enum EncoderError { FmtError(fmt::Error), BadHashmapKey, } impl Clone for EncoderError { fn clone(&self) -> Self { *self } } impl fmt::Debug for ErrorCode { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { error_str(*self).fmt(f) } } impl StdError for DecoderError { fn description(&self) -> &str { "decoder error" } fn cause(&self) -> Option<&StdError> { match *self { DecoderError::ParseError(ref e) => Some(e), _ => None, } } } impl fmt::Display for DecoderError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self, f) } } impl From<ParserError> for DecoderError { fn from(err: ParserError) -> DecoderError { DecoderError::ParseError(From::from(err)) } } impl StdError for ParserError { fn description(&self) -> &str { "failed to parse json" } } impl fmt::Display for ParserError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self, f) } } impl From<io::Error> for ParserError { fn from(err: io::Error) -> ParserError { ParserError::IoError(err) } } impl StdError for EncoderError { fn
(&self) -> &str { "encoder error" } } impl fmt::Display for EncoderError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self, f) } } impl From<fmt::Error> for EncoderError { fn from(err: fmt::Error) -> EncoderError { EncoderError::FmtError(err) } }
description
identifier_name
error.rs
use std::error::Error as StdError; use std::string; use std::{fmt, io}; /// The errors that can arise while parsing a JSON stream. #[derive(Clone, Copy, PartialEq)] pub enum ErrorCode { InvalidSyntax, InvalidNumber, EOFWhileParsingObject, EOFWhileParsingArray, EOFWhileParsingValue, EOFWhileParsingString, KeyMustBeAString, ExpectedColon, TrailingCharacters, TrailingComma, InvalidEscape, InvalidUnicodeCodePoint, LoneLeadingSurrogateInHexEscape,
NotUtf8, } #[derive(Debug)] pub enum ParserError { /// msg, line, col SyntaxError(ErrorCode, usize, usize), IoError(io::Error), } impl PartialEq for ParserError { fn eq(&self, other: &ParserError) -> bool { match (self, other) { (&ParserError::SyntaxError(msg0, line0, col0), &ParserError::SyntaxError(msg1, line1, col1)) => msg0 == msg1 && line0 == line1 && col0 == col1, (&ParserError::IoError(_), _) => false, (_, &ParserError::IoError(_)) => false, } } } /// Returns a readable error string for a given error code. pub fn error_str(error: ErrorCode) -> &'static str { match error { ErrorCode::InvalidSyntax => "invalid syntax", ErrorCode::InvalidNumber => "invalid number", ErrorCode::EOFWhileParsingObject => "EOF While parsing object", ErrorCode::EOFWhileParsingArray => "EOF While parsing array", ErrorCode::EOFWhileParsingValue => "EOF While parsing value", ErrorCode::EOFWhileParsingString => "EOF While parsing string", ErrorCode::KeyMustBeAString => "key must be a string", ErrorCode::ExpectedColon => "expected `:`", ErrorCode::TrailingCharacters => "trailing characters", ErrorCode::TrailingComma => "trailing comma", ErrorCode::InvalidEscape => "invalid escape", ErrorCode::UnrecognizedHex => "invalid \\u{ esc}ape (unrecognized hex)", ErrorCode::NotFourDigit => "invalid \\u{ esc}ape (not four digits)", ErrorCode::ControlCharacterInString => "unescaped control character in string", ErrorCode::NotUtf8 => "contents not utf-8", ErrorCode::InvalidUnicodeCodePoint => "invalid Unicode code point", ErrorCode::LoneLeadingSurrogateInHexEscape => "lone leading surrogate in hex escape", ErrorCode::UnexpectedEndOfHexEscape => "unexpected end of hex escape", } } #[derive(PartialEq, Debug)] pub enum DecoderError { ParseError(ParserError), ExpectedError(string::String, string::String), MissingFieldError(string::String), UnknownVariantError(string::String), ApplicationError(string::String), EOF, } #[derive(Copy, Debug)] pub enum EncoderError { FmtError(fmt::Error), BadHashmapKey, } impl Clone for EncoderError { fn clone(&self) -> Self { *self } } impl fmt::Debug for ErrorCode { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { error_str(*self).fmt(f) } } impl StdError for DecoderError { fn description(&self) -> &str { "decoder error" } fn cause(&self) -> Option<&StdError> { match *self { DecoderError::ParseError(ref e) => Some(e), _ => None, } } } impl fmt::Display for DecoderError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self, f) } } impl From<ParserError> for DecoderError { fn from(err: ParserError) -> DecoderError { DecoderError::ParseError(From::from(err)) } } impl StdError for ParserError { fn description(&self) -> &str { "failed to parse json" } } impl fmt::Display for ParserError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self, f) } } impl From<io::Error> for ParserError { fn from(err: io::Error) -> ParserError { ParserError::IoError(err) } } impl StdError for EncoderError { fn description(&self) -> &str { "encoder error" } } impl fmt::Display for EncoderError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self, f) } } impl From<fmt::Error> for EncoderError { fn from(err: fmt::Error) -> EncoderError { EncoderError::FmtError(err) } }
UnexpectedEndOfHexEscape, UnrecognizedHex, NotFourDigit, ControlCharacterInString,
random_line_split
error.rs
use std::error::Error as StdError; use std::string; use std::{fmt, io}; /// The errors that can arise while parsing a JSON stream. #[derive(Clone, Copy, PartialEq)] pub enum ErrorCode { InvalidSyntax, InvalidNumber, EOFWhileParsingObject, EOFWhileParsingArray, EOFWhileParsingValue, EOFWhileParsingString, KeyMustBeAString, ExpectedColon, TrailingCharacters, TrailingComma, InvalidEscape, InvalidUnicodeCodePoint, LoneLeadingSurrogateInHexEscape, UnexpectedEndOfHexEscape, UnrecognizedHex, NotFourDigit, ControlCharacterInString, NotUtf8, } #[derive(Debug)] pub enum ParserError { /// msg, line, col SyntaxError(ErrorCode, usize, usize), IoError(io::Error), } impl PartialEq for ParserError { fn eq(&self, other: &ParserError) -> bool { match (self, other) { (&ParserError::SyntaxError(msg0, line0, col0), &ParserError::SyntaxError(msg1, line1, col1)) => msg0 == msg1 && line0 == line1 && col0 == col1, (&ParserError::IoError(_), _) => false, (_, &ParserError::IoError(_)) => false, } } } /// Returns a readable error string for a given error code. pub fn error_str(error: ErrorCode) -> &'static str
#[derive(PartialEq, Debug)] pub enum DecoderError { ParseError(ParserError), ExpectedError(string::String, string::String), MissingFieldError(string::String), UnknownVariantError(string::String), ApplicationError(string::String), EOF, } #[derive(Copy, Debug)] pub enum EncoderError { FmtError(fmt::Error), BadHashmapKey, } impl Clone for EncoderError { fn clone(&self) -> Self { *self } } impl fmt::Debug for ErrorCode { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { error_str(*self).fmt(f) } } impl StdError for DecoderError { fn description(&self) -> &str { "decoder error" } fn cause(&self) -> Option<&StdError> { match *self { DecoderError::ParseError(ref e) => Some(e), _ => None, } } } impl fmt::Display for DecoderError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self, f) } } impl From<ParserError> for DecoderError { fn from(err: ParserError) -> DecoderError { DecoderError::ParseError(From::from(err)) } } impl StdError for ParserError { fn description(&self) -> &str { "failed to parse json" } } impl fmt::Display for ParserError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self, f) } } impl From<io::Error> for ParserError { fn from(err: io::Error) -> ParserError { ParserError::IoError(err) } } impl StdError for EncoderError { fn description(&self) -> &str { "encoder error" } } impl fmt::Display for EncoderError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self, f) } } impl From<fmt::Error> for EncoderError { fn from(err: fmt::Error) -> EncoderError { EncoderError::FmtError(err) } }
{ match error { ErrorCode::InvalidSyntax => "invalid syntax", ErrorCode::InvalidNumber => "invalid number", ErrorCode::EOFWhileParsingObject => "EOF While parsing object", ErrorCode::EOFWhileParsingArray => "EOF While parsing array", ErrorCode::EOFWhileParsingValue => "EOF While parsing value", ErrorCode::EOFWhileParsingString => "EOF While parsing string", ErrorCode::KeyMustBeAString => "key must be a string", ErrorCode::ExpectedColon => "expected `:`", ErrorCode::TrailingCharacters => "trailing characters", ErrorCode::TrailingComma => "trailing comma", ErrorCode::InvalidEscape => "invalid escape", ErrorCode::UnrecognizedHex => "invalid \\u{ esc}ape (unrecognized hex)", ErrorCode::NotFourDigit => "invalid \\u{ esc}ape (not four digits)", ErrorCode::ControlCharacterInString => "unescaped control character in string", ErrorCode::NotUtf8 => "contents not utf-8", ErrorCode::InvalidUnicodeCodePoint => "invalid Unicode code point", ErrorCode::LoneLeadingSurrogateInHexEscape => "lone leading surrogate in hex escape", ErrorCode::UnexpectedEndOfHexEscape => "unexpected end of hex escape", } }
identifier_body
traits.rs
// Copyright (C) 2017-2020 Free Software Foundation, Inc. // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #![allow(warnings)] pub trait T { } impl T for f64 { } impl T for u8 { } pub fn main()
{ let d = 23.5f64; let u = 23u8; let td = &d as &T; let tu = &u as &T; println!(""); // set breakpoint here }
identifier_body
traits.rs
// Copyright (C) 2017-2020 Free Software Foundation, Inc. // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #![allow(warnings)] pub trait T { } impl T for f64 { } impl T for u8 { } pub fn main() { let d = 23.5f64; let u = 23u8; let td = &d as &T; let tu = &u as &T;
}
println!(""); // set breakpoint here
random_line_split
traits.rs
// Copyright (C) 2017-2020 Free Software Foundation, Inc. // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #![allow(warnings)] pub trait T { } impl T for f64 { } impl T for u8 { } pub fn
() { let d = 23.5f64; let u = 23u8; let td = &d as &T; let tu = &u as &T; println!(""); // set breakpoint here }
main
identifier_name
index.js
var run_tl = new TimelineLite({ onComplete: function() { run_tl.play(0); }, }), jump_tl = new TimelineLite({ paused:true, onComplete:function() { run_tl.play(0); } }), dur = 0.125; TweenLite.defaultEase = Linear.easeNone; run_tl.timeScale(1.25); run_tl.add("Step") .add(bodyTl(), "Step") .add(armsTl(), "Step") .add(legRTl(), "Step") .add(legLTl(), "Step") // Running Methods function armsTl()
function bodyTl() { var body_tl = new TimelineLite(); body_tl.add(bodyBounce()) .add(bodyBounce()) console.log("Body TL", body_tl.totalDuration()); return body_tl; } function bodyBounce() { var tl = new TimelineLite(); tl.add("Up") .to(momo, dur, { y: "-50", ease: Power2.easeInOut }, "Up") .to(shadow, dur, {scale: 0.98, opacity: 0.9, transformOrigin: "50% 50%", ease: Power2.easeInOut}, "Up") .add("Down") .to(momo, dur, { y: "0", ease: Power2.easeIn }, "Down") .to(shadow, dur, { scale: 1, opacity: 1, ease: Power2.easeIn }, "Down") .to(cap, dur, { y: "-50", ease: Power2.easeInOut }, "Up+=" + dur * 0.8) .to(cap, dur, { y: "0", ease: Power2.easeIn }) return tl; } function legLTl() { var tl = new TimelineLite(); tl.add("Start").set(legL, {x: "-30",y: "10"}) .to(legL, dur * 2, { y: "-30", rotation: "30", transformOrigin: "50% 0" }) .to(legL, dur, { x: 0, y: 0, rotation: 0 }) .to(legL, dur, { x: "80", y: "10", rotation: 0 }) .to(legL, dur * 2, { x: "-30" }) console.log("LegL:", tl.totalDuration()); return tl; } function legRTl() { var tl = new TimelineLite(); tl .set(legL, {y:10}) .to(legR, dur, { y: "10", x: "80" }) .to(legR, dur * 2, { x: "-30" }) .to(legR, dur * 2, { y: "-30", rotation: "30", transformOrigin: "50% 0" }) .to(legR, dur, { x: 0, y: 0, rotation: 0 }) console.log("LegR:", tl.totalDuration()); return tl; } // Jumping Methods jump_tl.add("Up") .to(momo, dur*2, {y:"-300", ease:Power2.easeInOut}, "Up+="+dur*0.3) .to(shadow, dur*2, {scale:0.6, autoAlpha:0.5, transformOrigin:"50% 50%", ease:Power2.easeInOut}, "Up+="+dur*0.3) .to(legR, dur, {y:"40", rotation:"20", transformOrigin:"50% 0", ease:Power2.easeInOut}, "Up+="+dur*0.3) .to(face, dur, {y:"30", ease:Power4.easeInOut}, "Up+="+dur) .to(armL, dur*2, {y:"-200", x:"50", ease:Power4.easeOut}, "Up") .to(armR, dur*2, {y:"50", x:"-50", ease:Power4.easeOut}, "Up+="+dur*0.3) .set([openR,openL], {autoAlpha:0}) .set([blinkR,blinkL], {autoAlpha:1}) .add("Down") .to(momo, dur*2, {y:"20", ease:Power2.easeIn}, "Down") .to(shadow, dur*2, {scale:1.01, autoAlpha:1, ease:Power2.easeIn}, "Down") .staggerTo([legL,legR], dur, {y:"-20", rotation:0, ease:Power2.easeInOut}, 0.1, "Down") .to(legL, dur, {x:"30", rotation:"-20", transformOrigin:"50% 0", ease:Power2.easeInOut}, "Down+="+dur*0.5) .to(face, dur, {y:"-30", ease:Power4.easeInOut}, "Down+="+dur) .to(armL, dur*2, {y:"-400", x:0, ease:Power2.easeIn}, "Down") .to(armR, dur*2, {y:"-50", x:"-50", ease:Power2.easeInOut}, "Down") .to(cap, dur*2, {y:"-200", rotation:"-20", ease:Power2.easeIn}, "Down") .set(legR, {x:0}) .set(legL, {x:"-30"}) .add("Bounce") .set(legL, {x:0, rotation:0}) .set([openR,openL], {autoAlpha:1}) .set([blinkR,blinkL], {autoAlpha:0}) .to(momo, dur*2, {y:0, ease:Power2.easeOut}, "Bounce") .to([legL,legR], dur*2, {y:10, ease:Power2.easeOut}, "Bounce") .to(shadow, dur*2, {scale:1, ease:Power2.easeIn}, "Bounce") .to([armL,armR,face], dur*2, {y:0, x:0, ease:Back.easeOut}, "Bounce") .to(cap, dur*4, {y:0, rotation:0, ease:Bounce.easeOut}, "Bounce") // AUDIO // Looping Theme var audio = new Audio('https://s3-us-west-2.amazonaws.com/s.cdpn.io/259155/momoBros.mp3'); audio.loop = true; audio.play(); // Jump var jumpFx = new Audio('https://s3-us-west-2.amazonaws.com/s.cdpn.io/259155/MomoJump.mp3'); var toggle = document.getElementById('mute'); toggle.addEventListener('click', function() { if(!audio.paused) { audio.pause(); } else { audio.play(); } }) // BUTTON BEHAVIOUR var btn = document.querySelector('button'); btn.addEventListener('click', function(e) { if(!jump_tl.isActive()) { jump_tl.play(0); jumpFx.play(); run_tl.pause(); } // if (run_tl.isActive()) { // } else { // run_tl.play(); // } });
{ var arms_tl = new TimelineLite(); arms_tl.add("Start") .to(armR, dur * 3, { x: "150", ease: Power1.easeInOut }, "Start") .to(armL, dur * 2.75, { x: "-100", ease: Power1.easeInOut }, "Start") .add("Return") .to(armR, dur * 2.5, { x: "0", ease: Power1.easeInOut }, "Return") .to(armL, dur * 3, { x: "0", ease: Power1.easeInOut }, "Return") console.log("Arms TL", arms_tl.totalDuration()); return arms_tl; }
identifier_body
index.js
var run_tl = new TimelineLite({ onComplete: function() { run_tl.play(0); }, }), jump_tl = new TimelineLite({ paused:true, onComplete:function() { run_tl.play(0); } }), dur = 0.125; TweenLite.defaultEase = Linear.easeNone; run_tl.timeScale(1.25); run_tl.add("Step") .add(bodyTl(), "Step") .add(armsTl(), "Step") .add(legRTl(), "Step") .add(legLTl(), "Step") // Running Methods function armsTl() { var arms_tl = new TimelineLite(); arms_tl.add("Start") .to(armR, dur * 3, { x: "150", ease: Power1.easeInOut }, "Start") .to(armL, dur * 2.75, { x: "-100", ease: Power1.easeInOut }, "Start") .add("Return") .to(armR, dur * 2.5, { x: "0", ease: Power1.easeInOut }, "Return") .to(armL, dur * 3, { x: "0", ease: Power1.easeInOut }, "Return") console.log("Arms TL", arms_tl.totalDuration()); return arms_tl; } function bodyTl() { var body_tl = new TimelineLite(); body_tl.add(bodyBounce()) .add(bodyBounce()) console.log("Body TL", body_tl.totalDuration()); return body_tl; } function bodyBounce() { var tl = new TimelineLite(); tl.add("Up") .to(momo, dur, { y: "-50", ease: Power2.easeInOut }, "Up") .to(shadow, dur, {scale: 0.98, opacity: 0.9, transformOrigin: "50% 50%", ease: Power2.easeInOut}, "Up") .add("Down") .to(momo, dur, { y: "0", ease: Power2.easeIn }, "Down") .to(shadow, dur, { scale: 1, opacity: 1, ease: Power2.easeIn }, "Down") .to(cap, dur, { y: "-50", ease: Power2.easeInOut }, "Up+=" + dur * 0.8) .to(cap, dur, { y: "0", ease: Power2.easeIn }) return tl; }
var tl = new TimelineLite(); tl.add("Start").set(legL, {x: "-30",y: "10"}) .to(legL, dur * 2, { y: "-30", rotation: "30", transformOrigin: "50% 0" }) .to(legL, dur, { x: 0, y: 0, rotation: 0 }) .to(legL, dur, { x: "80", y: "10", rotation: 0 }) .to(legL, dur * 2, { x: "-30" }) console.log("LegL:", tl.totalDuration()); return tl; } function legRTl() { var tl = new TimelineLite(); tl .set(legL, {y:10}) .to(legR, dur, { y: "10", x: "80" }) .to(legR, dur * 2, { x: "-30" }) .to(legR, dur * 2, { y: "-30", rotation: "30", transformOrigin: "50% 0" }) .to(legR, dur, { x: 0, y: 0, rotation: 0 }) console.log("LegR:", tl.totalDuration()); return tl; } // Jumping Methods jump_tl.add("Up") .to(momo, dur*2, {y:"-300", ease:Power2.easeInOut}, "Up+="+dur*0.3) .to(shadow, dur*2, {scale:0.6, autoAlpha:0.5, transformOrigin:"50% 50%", ease:Power2.easeInOut}, "Up+="+dur*0.3) .to(legR, dur, {y:"40", rotation:"20", transformOrigin:"50% 0", ease:Power2.easeInOut}, "Up+="+dur*0.3) .to(face, dur, {y:"30", ease:Power4.easeInOut}, "Up+="+dur) .to(armL, dur*2, {y:"-200", x:"50", ease:Power4.easeOut}, "Up") .to(armR, dur*2, {y:"50", x:"-50", ease:Power4.easeOut}, "Up+="+dur*0.3) .set([openR,openL], {autoAlpha:0}) .set([blinkR,blinkL], {autoAlpha:1}) .add("Down") .to(momo, dur*2, {y:"20", ease:Power2.easeIn}, "Down") .to(shadow, dur*2, {scale:1.01, autoAlpha:1, ease:Power2.easeIn}, "Down") .staggerTo([legL,legR], dur, {y:"-20", rotation:0, ease:Power2.easeInOut}, 0.1, "Down") .to(legL, dur, {x:"30", rotation:"-20", transformOrigin:"50% 0", ease:Power2.easeInOut}, "Down+="+dur*0.5) .to(face, dur, {y:"-30", ease:Power4.easeInOut}, "Down+="+dur) .to(armL, dur*2, {y:"-400", x:0, ease:Power2.easeIn}, "Down") .to(armR, dur*2, {y:"-50", x:"-50", ease:Power2.easeInOut}, "Down") .to(cap, dur*2, {y:"-200", rotation:"-20", ease:Power2.easeIn}, "Down") .set(legR, {x:0}) .set(legL, {x:"-30"}) .add("Bounce") .set(legL, {x:0, rotation:0}) .set([openR,openL], {autoAlpha:1}) .set([blinkR,blinkL], {autoAlpha:0}) .to(momo, dur*2, {y:0, ease:Power2.easeOut}, "Bounce") .to([legL,legR], dur*2, {y:10, ease:Power2.easeOut}, "Bounce") .to(shadow, dur*2, {scale:1, ease:Power2.easeIn}, "Bounce") .to([armL,armR,face], dur*2, {y:0, x:0, ease:Back.easeOut}, "Bounce") .to(cap, dur*4, {y:0, rotation:0, ease:Bounce.easeOut}, "Bounce") // AUDIO // Looping Theme var audio = new Audio('https://s3-us-west-2.amazonaws.com/s.cdpn.io/259155/momoBros.mp3'); audio.loop = true; audio.play(); // Jump var jumpFx = new Audio('https://s3-us-west-2.amazonaws.com/s.cdpn.io/259155/MomoJump.mp3'); var toggle = document.getElementById('mute'); toggle.addEventListener('click', function() { if(!audio.paused) { audio.pause(); } else { audio.play(); } }) // BUTTON BEHAVIOUR var btn = document.querySelector('button'); btn.addEventListener('click', function(e) { if(!jump_tl.isActive()) { jump_tl.play(0); jumpFx.play(); run_tl.pause(); } // if (run_tl.isActive()) { // } else { // run_tl.play(); // } });
function legLTl() {
random_line_split
index.js
var run_tl = new TimelineLite({ onComplete: function() { run_tl.play(0); }, }), jump_tl = new TimelineLite({ paused:true, onComplete:function() { run_tl.play(0); } }), dur = 0.125; TweenLite.defaultEase = Linear.easeNone; run_tl.timeScale(1.25); run_tl.add("Step") .add(bodyTl(), "Step") .add(armsTl(), "Step") .add(legRTl(), "Step") .add(legLTl(), "Step") // Running Methods function armsTl() { var arms_tl = new TimelineLite(); arms_tl.add("Start") .to(armR, dur * 3, { x: "150", ease: Power1.easeInOut }, "Start") .to(armL, dur * 2.75, { x: "-100", ease: Power1.easeInOut }, "Start") .add("Return") .to(armR, dur * 2.5, { x: "0", ease: Power1.easeInOut }, "Return") .to(armL, dur * 3, { x: "0", ease: Power1.easeInOut }, "Return") console.log("Arms TL", arms_tl.totalDuration()); return arms_tl; } function bodyTl() { var body_tl = new TimelineLite(); body_tl.add(bodyBounce()) .add(bodyBounce()) console.log("Body TL", body_tl.totalDuration()); return body_tl; } function bodyBounce() { var tl = new TimelineLite(); tl.add("Up") .to(momo, dur, { y: "-50", ease: Power2.easeInOut }, "Up") .to(shadow, dur, {scale: 0.98, opacity: 0.9, transformOrigin: "50% 50%", ease: Power2.easeInOut}, "Up") .add("Down") .to(momo, dur, { y: "0", ease: Power2.easeIn }, "Down") .to(shadow, dur, { scale: 1, opacity: 1, ease: Power2.easeIn }, "Down") .to(cap, dur, { y: "-50", ease: Power2.easeInOut }, "Up+=" + dur * 0.8) .to(cap, dur, { y: "0", ease: Power2.easeIn }) return tl; } function legLTl() { var tl = new TimelineLite(); tl.add("Start").set(legL, {x: "-30",y: "10"}) .to(legL, dur * 2, { y: "-30", rotation: "30", transformOrigin: "50% 0" }) .to(legL, dur, { x: 0, y: 0, rotation: 0 }) .to(legL, dur, { x: "80", y: "10", rotation: 0 }) .to(legL, dur * 2, { x: "-30" }) console.log("LegL:", tl.totalDuration()); return tl; } function legRTl() { var tl = new TimelineLite(); tl .set(legL, {y:10}) .to(legR, dur, { y: "10", x: "80" }) .to(legR, dur * 2, { x: "-30" }) .to(legR, dur * 2, { y: "-30", rotation: "30", transformOrigin: "50% 0" }) .to(legR, dur, { x: 0, y: 0, rotation: 0 }) console.log("LegR:", tl.totalDuration()); return tl; } // Jumping Methods jump_tl.add("Up") .to(momo, dur*2, {y:"-300", ease:Power2.easeInOut}, "Up+="+dur*0.3) .to(shadow, dur*2, {scale:0.6, autoAlpha:0.5, transformOrigin:"50% 50%", ease:Power2.easeInOut}, "Up+="+dur*0.3) .to(legR, dur, {y:"40", rotation:"20", transformOrigin:"50% 0", ease:Power2.easeInOut}, "Up+="+dur*0.3) .to(face, dur, {y:"30", ease:Power4.easeInOut}, "Up+="+dur) .to(armL, dur*2, {y:"-200", x:"50", ease:Power4.easeOut}, "Up") .to(armR, dur*2, {y:"50", x:"-50", ease:Power4.easeOut}, "Up+="+dur*0.3) .set([openR,openL], {autoAlpha:0}) .set([blinkR,blinkL], {autoAlpha:1}) .add("Down") .to(momo, dur*2, {y:"20", ease:Power2.easeIn}, "Down") .to(shadow, dur*2, {scale:1.01, autoAlpha:1, ease:Power2.easeIn}, "Down") .staggerTo([legL,legR], dur, {y:"-20", rotation:0, ease:Power2.easeInOut}, 0.1, "Down") .to(legL, dur, {x:"30", rotation:"-20", transformOrigin:"50% 0", ease:Power2.easeInOut}, "Down+="+dur*0.5) .to(face, dur, {y:"-30", ease:Power4.easeInOut}, "Down+="+dur) .to(armL, dur*2, {y:"-400", x:0, ease:Power2.easeIn}, "Down") .to(armR, dur*2, {y:"-50", x:"-50", ease:Power2.easeInOut}, "Down") .to(cap, dur*2, {y:"-200", rotation:"-20", ease:Power2.easeIn}, "Down") .set(legR, {x:0}) .set(legL, {x:"-30"}) .add("Bounce") .set(legL, {x:0, rotation:0}) .set([openR,openL], {autoAlpha:1}) .set([blinkR,blinkL], {autoAlpha:0}) .to(momo, dur*2, {y:0, ease:Power2.easeOut}, "Bounce") .to([legL,legR], dur*2, {y:10, ease:Power2.easeOut}, "Bounce") .to(shadow, dur*2, {scale:1, ease:Power2.easeIn}, "Bounce") .to([armL,armR,face], dur*2, {y:0, x:0, ease:Back.easeOut}, "Bounce") .to(cap, dur*4, {y:0, rotation:0, ease:Bounce.easeOut}, "Bounce") // AUDIO // Looping Theme var audio = new Audio('https://s3-us-west-2.amazonaws.com/s.cdpn.io/259155/momoBros.mp3'); audio.loop = true; audio.play(); // Jump var jumpFx = new Audio('https://s3-us-west-2.amazonaws.com/s.cdpn.io/259155/MomoJump.mp3'); var toggle = document.getElementById('mute'); toggle.addEventListener('click', function() { if(!audio.paused) { audio.pause(); } else
}) // BUTTON BEHAVIOUR var btn = document.querySelector('button'); btn.addEventListener('click', function(e) { if(!jump_tl.isActive()) { jump_tl.play(0); jumpFx.play(); run_tl.pause(); } // if (run_tl.isActive()) { // } else { // run_tl.play(); // } });
{ audio.play(); }
conditional_block
index.js
var run_tl = new TimelineLite({ onComplete: function() { run_tl.play(0); }, }), jump_tl = new TimelineLite({ paused:true, onComplete:function() { run_tl.play(0); } }), dur = 0.125; TweenLite.defaultEase = Linear.easeNone; run_tl.timeScale(1.25); run_tl.add("Step") .add(bodyTl(), "Step") .add(armsTl(), "Step") .add(legRTl(), "Step") .add(legLTl(), "Step") // Running Methods function armsTl() { var arms_tl = new TimelineLite(); arms_tl.add("Start") .to(armR, dur * 3, { x: "150", ease: Power1.easeInOut }, "Start") .to(armL, dur * 2.75, { x: "-100", ease: Power1.easeInOut }, "Start") .add("Return") .to(armR, dur * 2.5, { x: "0", ease: Power1.easeInOut }, "Return") .to(armL, dur * 3, { x: "0", ease: Power1.easeInOut }, "Return") console.log("Arms TL", arms_tl.totalDuration()); return arms_tl; } function bodyTl() { var body_tl = new TimelineLite(); body_tl.add(bodyBounce()) .add(bodyBounce()) console.log("Body TL", body_tl.totalDuration()); return body_tl; } function
() { var tl = new TimelineLite(); tl.add("Up") .to(momo, dur, { y: "-50", ease: Power2.easeInOut }, "Up") .to(shadow, dur, {scale: 0.98, opacity: 0.9, transformOrigin: "50% 50%", ease: Power2.easeInOut}, "Up") .add("Down") .to(momo, dur, { y: "0", ease: Power2.easeIn }, "Down") .to(shadow, dur, { scale: 1, opacity: 1, ease: Power2.easeIn }, "Down") .to(cap, dur, { y: "-50", ease: Power2.easeInOut }, "Up+=" + dur * 0.8) .to(cap, dur, { y: "0", ease: Power2.easeIn }) return tl; } function legLTl() { var tl = new TimelineLite(); tl.add("Start").set(legL, {x: "-30",y: "10"}) .to(legL, dur * 2, { y: "-30", rotation: "30", transformOrigin: "50% 0" }) .to(legL, dur, { x: 0, y: 0, rotation: 0 }) .to(legL, dur, { x: "80", y: "10", rotation: 0 }) .to(legL, dur * 2, { x: "-30" }) console.log("LegL:", tl.totalDuration()); return tl; } function legRTl() { var tl = new TimelineLite(); tl .set(legL, {y:10}) .to(legR, dur, { y: "10", x: "80" }) .to(legR, dur * 2, { x: "-30" }) .to(legR, dur * 2, { y: "-30", rotation: "30", transformOrigin: "50% 0" }) .to(legR, dur, { x: 0, y: 0, rotation: 0 }) console.log("LegR:", tl.totalDuration()); return tl; } // Jumping Methods jump_tl.add("Up") .to(momo, dur*2, {y:"-300", ease:Power2.easeInOut}, "Up+="+dur*0.3) .to(shadow, dur*2, {scale:0.6, autoAlpha:0.5, transformOrigin:"50% 50%", ease:Power2.easeInOut}, "Up+="+dur*0.3) .to(legR, dur, {y:"40", rotation:"20", transformOrigin:"50% 0", ease:Power2.easeInOut}, "Up+="+dur*0.3) .to(face, dur, {y:"30", ease:Power4.easeInOut}, "Up+="+dur) .to(armL, dur*2, {y:"-200", x:"50", ease:Power4.easeOut}, "Up") .to(armR, dur*2, {y:"50", x:"-50", ease:Power4.easeOut}, "Up+="+dur*0.3) .set([openR,openL], {autoAlpha:0}) .set([blinkR,blinkL], {autoAlpha:1}) .add("Down") .to(momo, dur*2, {y:"20", ease:Power2.easeIn}, "Down") .to(shadow, dur*2, {scale:1.01, autoAlpha:1, ease:Power2.easeIn}, "Down") .staggerTo([legL,legR], dur, {y:"-20", rotation:0, ease:Power2.easeInOut}, 0.1, "Down") .to(legL, dur, {x:"30", rotation:"-20", transformOrigin:"50% 0", ease:Power2.easeInOut}, "Down+="+dur*0.5) .to(face, dur, {y:"-30", ease:Power4.easeInOut}, "Down+="+dur) .to(armL, dur*2, {y:"-400", x:0, ease:Power2.easeIn}, "Down") .to(armR, dur*2, {y:"-50", x:"-50", ease:Power2.easeInOut}, "Down") .to(cap, dur*2, {y:"-200", rotation:"-20", ease:Power2.easeIn}, "Down") .set(legR, {x:0}) .set(legL, {x:"-30"}) .add("Bounce") .set(legL, {x:0, rotation:0}) .set([openR,openL], {autoAlpha:1}) .set([blinkR,blinkL], {autoAlpha:0}) .to(momo, dur*2, {y:0, ease:Power2.easeOut}, "Bounce") .to([legL,legR], dur*2, {y:10, ease:Power2.easeOut}, "Bounce") .to(shadow, dur*2, {scale:1, ease:Power2.easeIn}, "Bounce") .to([armL,armR,face], dur*2, {y:0, x:0, ease:Back.easeOut}, "Bounce") .to(cap, dur*4, {y:0, rotation:0, ease:Bounce.easeOut}, "Bounce") // AUDIO // Looping Theme var audio = new Audio('https://s3-us-west-2.amazonaws.com/s.cdpn.io/259155/momoBros.mp3'); audio.loop = true; audio.play(); // Jump var jumpFx = new Audio('https://s3-us-west-2.amazonaws.com/s.cdpn.io/259155/MomoJump.mp3'); var toggle = document.getElementById('mute'); toggle.addEventListener('click', function() { if(!audio.paused) { audio.pause(); } else { audio.play(); } }) // BUTTON BEHAVIOUR var btn = document.querySelector('button'); btn.addEventListener('click', function(e) { if(!jump_tl.isActive()) { jump_tl.play(0); jumpFx.play(); run_tl.pause(); } // if (run_tl.isActive()) { // } else { // run_tl.play(); // } });
bodyBounce
identifier_name
create_objects.py
# -*- coding: utf-8 -*- # Demandlib import logging import oemof.solph as solph import reegis_hp.berlin_hp.electricity as electricity import pandas as pd import demandlib.bdew as bdew import demandlib.particular_profiles as pprofiles import reegis_hp.berlin_hp.prepare_data as prepare_data def heating_systems(esystem, dfull, add_elec, p):
power_plants = prepare_data.chp_berlin(p) time_index = esystem.time_idx temperature_path = '/home/uwe/rli-lokal/git_home/demandlib/examples' temperature_file = temperature_path + '/example_data.csv' temperature = pd.read_csv(temperature_file)['temperature'] sli = pd.Series(list(temperature.loc[:23]), index=list(range(8760, 8784))) temperature = temperature.append(sli) temperature = temperature.iloc[0:len(time_index)] heatbus = dict() hd = dict() auxiliary_energy = 0 print(dfull) for h in dfull.keys(): hd.setdefault(h, 0) lsink = 'demand_{0}'.format(h) lbus = 'bus_{0}'.format(h) ltransf = '{0}'.format(h) lres_bus = 'bus_{0}'.format(p.heating2resource[h]) for b in dfull[h].keys(): if b.upper() in p.bdew_types: bc = 0 if b.upper() in ['EFH', 'MFH']: bc = 1 hd[h] += bdew.HeatBuilding( time_index, temperature=temperature, shlp_type=b, building_class=bc, wind_class=1, annual_heat_demand=dfull[h][b], name=h ).get_bdew_profile() if b.upper() in ['EFH', 'MFH']: print(h, 'in') auxiliary_energy += bdew.HeatBuilding( time_index, temperature=temperature, shlp_type=b, building_class=bc, wind_class=1, annual_heat_demand=add_elec[h][b], name=h ).get_bdew_profile() elif b in ['i', ]: hd[h] += pprofiles.IndustrialLoadProfile( time_index).simple_profile(annual_demand=dfull[h][b]) else: logging.error('Demandlib typ "{0}" not found.'.format(b)) heatbus[h] = solph.Bus(label=lbus) solph.Sink(label=lsink, inputs={heatbus[h]: solph.Flow( actual_value=hd[h].div(hd[h].max()), fixed=True, nominal_value=hd[h].max())}) if 'district' not in h: if lres_bus not in esystem.groups: solph.Bus(label=lres_bus) solph.LinearTransformer( label=ltransf, inputs={esystem.groups[lres_bus]: solph.Flow()}, outputs={heatbus[h]: solph.Flow( nominal_value=hd[h].max(), variable_costs=0)}, conversion_factors={heatbus[h]: 1}) else: for pp in power_plants[h].index: lres_bus = 'bus_' + pp if lres_bus not in esystem.groups: solph.Bus(label=lres_bus) solph.LinearTransformer( label='pp_chp_{0}_{1}'.format(h, pp), inputs={esystem.groups[lres_bus]: solph.Flow()}, outputs={ esystem.groups['bus_el']: solph.Flow( nominal_value=power_plants[h]['power_el'][pp]), heatbus[h]: solph.Flow( nominal_value=power_plants[h]['power_th'][pp])}, conversion_factors={esystem.groups['bus_el']: 0.3, heatbus[h]: 0.4}) from matplotlib import pyplot as plt hd_df = pd. DataFrame(hd) print(hd_df.sum().sum()) print('z_max:', hd_df['district_z'].max()) print('dz_max:', hd_df['district_dz'].max()) print('z_sum:', hd_df['district_z'].sum()) print('dz_sum:', hd_df['district_dz'].sum()) hd_df.plot(colormap='Spectral') hd_df.to_csv('/home/uwe/hd.csv') plt.show() solph.Sink(label='auxiliary_energy', inputs={esystem.groups['bus_el']: solph.Flow( actual_value=auxiliary_energy.div(auxiliary_energy.max()), fixed=True, nominal_value=auxiliary_energy.max())}) # Create sinks # Get normalise demand and maximum value of electricity usage electricity_usage = electricity.DemandElec(time_index) normalised_demand, max_demand = electricity_usage.solph_sink( resample='H', reduce=auxiliary_energy) sum_demand = normalised_demand.sum() * max_demand print("delec:", "{:.2E}".format(sum_demand)) solph.Sink(label='elec_demand', inputs={esystem.groups['bus_el']: solph.Flow( actual_value=normalised_demand, fixed=True, nominal_value=max_demand)})
identifier_body
create_objects.py
# -*- coding: utf-8 -*- # Demandlib import logging import oemof.solph as solph import reegis_hp.berlin_hp.electricity as electricity import pandas as pd import demandlib.bdew as bdew import demandlib.particular_profiles as pprofiles import reegis_hp.berlin_hp.prepare_data as prepare_data def
(esystem, dfull, add_elec, p): power_plants = prepare_data.chp_berlin(p) time_index = esystem.time_idx temperature_path = '/home/uwe/rli-lokal/git_home/demandlib/examples' temperature_file = temperature_path + '/example_data.csv' temperature = pd.read_csv(temperature_file)['temperature'] sli = pd.Series(list(temperature.loc[:23]), index=list(range(8760, 8784))) temperature = temperature.append(sli) temperature = temperature.iloc[0:len(time_index)] heatbus = dict() hd = dict() auxiliary_energy = 0 print(dfull) for h in dfull.keys(): hd.setdefault(h, 0) lsink = 'demand_{0}'.format(h) lbus = 'bus_{0}'.format(h) ltransf = '{0}'.format(h) lres_bus = 'bus_{0}'.format(p.heating2resource[h]) for b in dfull[h].keys(): if b.upper() in p.bdew_types: bc = 0 if b.upper() in ['EFH', 'MFH']: bc = 1 hd[h] += bdew.HeatBuilding( time_index, temperature=temperature, shlp_type=b, building_class=bc, wind_class=1, annual_heat_demand=dfull[h][b], name=h ).get_bdew_profile() if b.upper() in ['EFH', 'MFH']: print(h, 'in') auxiliary_energy += bdew.HeatBuilding( time_index, temperature=temperature, shlp_type=b, building_class=bc, wind_class=1, annual_heat_demand=add_elec[h][b], name=h ).get_bdew_profile() elif b in ['i', ]: hd[h] += pprofiles.IndustrialLoadProfile( time_index).simple_profile(annual_demand=dfull[h][b]) else: logging.error('Demandlib typ "{0}" not found.'.format(b)) heatbus[h] = solph.Bus(label=lbus) solph.Sink(label=lsink, inputs={heatbus[h]: solph.Flow( actual_value=hd[h].div(hd[h].max()), fixed=True, nominal_value=hd[h].max())}) if 'district' not in h: if lres_bus not in esystem.groups: solph.Bus(label=lres_bus) solph.LinearTransformer( label=ltransf, inputs={esystem.groups[lres_bus]: solph.Flow()}, outputs={heatbus[h]: solph.Flow( nominal_value=hd[h].max(), variable_costs=0)}, conversion_factors={heatbus[h]: 1}) else: for pp in power_plants[h].index: lres_bus = 'bus_' + pp if lres_bus not in esystem.groups: solph.Bus(label=lres_bus) solph.LinearTransformer( label='pp_chp_{0}_{1}'.format(h, pp), inputs={esystem.groups[lres_bus]: solph.Flow()}, outputs={ esystem.groups['bus_el']: solph.Flow( nominal_value=power_plants[h]['power_el'][pp]), heatbus[h]: solph.Flow( nominal_value=power_plants[h]['power_th'][pp])}, conversion_factors={esystem.groups['bus_el']: 0.3, heatbus[h]: 0.4}) from matplotlib import pyplot as plt hd_df = pd. DataFrame(hd) print(hd_df.sum().sum()) print('z_max:', hd_df['district_z'].max()) print('dz_max:', hd_df['district_dz'].max()) print('z_sum:', hd_df['district_z'].sum()) print('dz_sum:', hd_df['district_dz'].sum()) hd_df.plot(colormap='Spectral') hd_df.to_csv('/home/uwe/hd.csv') plt.show() solph.Sink(label='auxiliary_energy', inputs={esystem.groups['bus_el']: solph.Flow( actual_value=auxiliary_energy.div(auxiliary_energy.max()), fixed=True, nominal_value=auxiliary_energy.max())}) # Create sinks # Get normalise demand and maximum value of electricity usage electricity_usage = electricity.DemandElec(time_index) normalised_demand, max_demand = electricity_usage.solph_sink( resample='H', reduce=auxiliary_energy) sum_demand = normalised_demand.sum() * max_demand print("delec:", "{:.2E}".format(sum_demand)) solph.Sink(label='elec_demand', inputs={esystem.groups['bus_el']: solph.Flow( actual_value=normalised_demand, fixed=True, nominal_value=max_demand)})
heating_systems
identifier_name
create_objects.py
# -*- coding: utf-8 -*- # Demandlib import logging import oemof.solph as solph import reegis_hp.berlin_hp.electricity as electricity import pandas as pd import demandlib.bdew as bdew import demandlib.particular_profiles as pprofiles import reegis_hp.berlin_hp.prepare_data as prepare_data def heating_systems(esystem, dfull, add_elec, p): power_plants = prepare_data.chp_berlin(p) time_index = esystem.time_idx temperature_path = '/home/uwe/rli-lokal/git_home/demandlib/examples' temperature_file = temperature_path + '/example_data.csv' temperature = pd.read_csv(temperature_file)['temperature'] sli = pd.Series(list(temperature.loc[:23]), index=list(range(8760, 8784))) temperature = temperature.append(sli) temperature = temperature.iloc[0:len(time_index)] heatbus = dict() hd = dict() auxiliary_energy = 0 print(dfull) for h in dfull.keys(): hd.setdefault(h, 0) lsink = 'demand_{0}'.format(h) lbus = 'bus_{0}'.format(h) ltransf = '{0}'.format(h) lres_bus = 'bus_{0}'.format(p.heating2resource[h]) for b in dfull[h].keys(): if b.upper() in p.bdew_types: bc = 0 if b.upper() in ['EFH', 'MFH']: bc = 1 hd[h] += bdew.HeatBuilding( time_index, temperature=temperature, shlp_type=b, building_class=bc, wind_class=1, annual_heat_demand=dfull[h][b], name=h ).get_bdew_profile() if b.upper() in ['EFH', 'MFH']: print(h, 'in') auxiliary_energy += bdew.HeatBuilding( time_index, temperature=temperature, shlp_type=b, building_class=bc, wind_class=1, annual_heat_demand=add_elec[h][b], name=h ).get_bdew_profile() elif b in ['i', ]: hd[h] += pprofiles.IndustrialLoadProfile( time_index).simple_profile(annual_demand=dfull[h][b]) else:
heatbus[h] = solph.Bus(label=lbus) solph.Sink(label=lsink, inputs={heatbus[h]: solph.Flow( actual_value=hd[h].div(hd[h].max()), fixed=True, nominal_value=hd[h].max())}) if 'district' not in h: if lres_bus not in esystem.groups: solph.Bus(label=lres_bus) solph.LinearTransformer( label=ltransf, inputs={esystem.groups[lres_bus]: solph.Flow()}, outputs={heatbus[h]: solph.Flow( nominal_value=hd[h].max(), variable_costs=0)}, conversion_factors={heatbus[h]: 1}) else: for pp in power_plants[h].index: lres_bus = 'bus_' + pp if lres_bus not in esystem.groups: solph.Bus(label=lres_bus) solph.LinearTransformer( label='pp_chp_{0}_{1}'.format(h, pp), inputs={esystem.groups[lres_bus]: solph.Flow()}, outputs={ esystem.groups['bus_el']: solph.Flow( nominal_value=power_plants[h]['power_el'][pp]), heatbus[h]: solph.Flow( nominal_value=power_plants[h]['power_th'][pp])}, conversion_factors={esystem.groups['bus_el']: 0.3, heatbus[h]: 0.4}) from matplotlib import pyplot as plt hd_df = pd. DataFrame(hd) print(hd_df.sum().sum()) print('z_max:', hd_df['district_z'].max()) print('dz_max:', hd_df['district_dz'].max()) print('z_sum:', hd_df['district_z'].sum()) print('dz_sum:', hd_df['district_dz'].sum()) hd_df.plot(colormap='Spectral') hd_df.to_csv('/home/uwe/hd.csv') plt.show() solph.Sink(label='auxiliary_energy', inputs={esystem.groups['bus_el']: solph.Flow( actual_value=auxiliary_energy.div(auxiliary_energy.max()), fixed=True, nominal_value=auxiliary_energy.max())}) # Create sinks # Get normalise demand and maximum value of electricity usage electricity_usage = electricity.DemandElec(time_index) normalised_demand, max_demand = electricity_usage.solph_sink( resample='H', reduce=auxiliary_energy) sum_demand = normalised_demand.sum() * max_demand print("delec:", "{:.2E}".format(sum_demand)) solph.Sink(label='elec_demand', inputs={esystem.groups['bus_el']: solph.Flow( actual_value=normalised_demand, fixed=True, nominal_value=max_demand)})
logging.error('Demandlib typ "{0}" not found.'.format(b))
conditional_block
create_objects.py
# -*- coding: utf-8 -*- # Demandlib import logging import oemof.solph as solph import reegis_hp.berlin_hp.electricity as electricity import pandas as pd import demandlib.bdew as bdew import demandlib.particular_profiles as pprofiles import reegis_hp.berlin_hp.prepare_data as prepare_data def heating_systems(esystem, dfull, add_elec, p): power_plants = prepare_data.chp_berlin(p) time_index = esystem.time_idx temperature_path = '/home/uwe/rli-lokal/git_home/demandlib/examples' temperature_file = temperature_path + '/example_data.csv' temperature = pd.read_csv(temperature_file)['temperature'] sli = pd.Series(list(temperature.loc[:23]), index=list(range(8760, 8784))) temperature = temperature.append(sli) temperature = temperature.iloc[0:len(time_index)] heatbus = dict() hd = dict() auxiliary_energy = 0 print(dfull) for h in dfull.keys(): hd.setdefault(h, 0) lsink = 'demand_{0}'.format(h) lbus = 'bus_{0}'.format(h) ltransf = '{0}'.format(h) lres_bus = 'bus_{0}'.format(p.heating2resource[h]) for b in dfull[h].keys(): if b.upper() in p.bdew_types: bc = 0 if b.upper() in ['EFH', 'MFH']: bc = 1 hd[h] += bdew.HeatBuilding( time_index, temperature=temperature, shlp_type=b, building_class=bc, wind_class=1, annual_heat_demand=dfull[h][b], name=h ).get_bdew_profile() if b.upper() in ['EFH', 'MFH']: print(h, 'in') auxiliary_energy += bdew.HeatBuilding( time_index, temperature=temperature, shlp_type=b, building_class=bc, wind_class=1, annual_heat_demand=add_elec[h][b], name=h ).get_bdew_profile() elif b in ['i', ]: hd[h] += pprofiles.IndustrialLoadProfile( time_index).simple_profile(annual_demand=dfull[h][b]) else: logging.error('Demandlib typ "{0}" not found.'.format(b)) heatbus[h] = solph.Bus(label=lbus) solph.Sink(label=lsink, inputs={heatbus[h]: solph.Flow( actual_value=hd[h].div(hd[h].max()), fixed=True, nominal_value=hd[h].max())}) if 'district' not in h: if lres_bus not in esystem.groups: solph.Bus(label=lres_bus) solph.LinearTransformer( label=ltransf, inputs={esystem.groups[lres_bus]: solph.Flow()}, outputs={heatbus[h]: solph.Flow( nominal_value=hd[h].max(), variable_costs=0)}, conversion_factors={heatbus[h]: 1}) else: for pp in power_plants[h].index: lres_bus = 'bus_' + pp if lres_bus not in esystem.groups: solph.Bus(label=lres_bus)
esystem.groups['bus_el']: solph.Flow( nominal_value=power_plants[h]['power_el'][pp]), heatbus[h]: solph.Flow( nominal_value=power_plants[h]['power_th'][pp])}, conversion_factors={esystem.groups['bus_el']: 0.3, heatbus[h]: 0.4}) from matplotlib import pyplot as plt hd_df = pd. DataFrame(hd) print(hd_df.sum().sum()) print('z_max:', hd_df['district_z'].max()) print('dz_max:', hd_df['district_dz'].max()) print('z_sum:', hd_df['district_z'].sum()) print('dz_sum:', hd_df['district_dz'].sum()) hd_df.plot(colormap='Spectral') hd_df.to_csv('/home/uwe/hd.csv') plt.show() solph.Sink(label='auxiliary_energy', inputs={esystem.groups['bus_el']: solph.Flow( actual_value=auxiliary_energy.div(auxiliary_energy.max()), fixed=True, nominal_value=auxiliary_energy.max())}) # Create sinks # Get normalise demand and maximum value of electricity usage electricity_usage = electricity.DemandElec(time_index) normalised_demand, max_demand = electricity_usage.solph_sink( resample='H', reduce=auxiliary_energy) sum_demand = normalised_demand.sum() * max_demand print("delec:", "{:.2E}".format(sum_demand)) solph.Sink(label='elec_demand', inputs={esystem.groups['bus_el']: solph.Flow( actual_value=normalised_demand, fixed=True, nominal_value=max_demand)})
solph.LinearTransformer( label='pp_chp_{0}_{1}'.format(h, pp), inputs={esystem.groups[lres_bus]: solph.Flow()}, outputs={
random_line_split
test_local.py
import numpy as np def test_prepare_abi_connectivity_maps(): from samri.fetch.local import prepare_abi_connectivity_maps prepare_abi_connectivity_maps('Ventral_tegmental_area', invert_lr_experiments=[ "127651139", "127796728", "127798146", "127867804", "156314762", "160539283", "160540751", "165975096", "166054222", "171021829", "175736945", "278178382", "292958638", "301062306", "304337288", ], ) def test_prepare_feature_map():
def test_summary_atlas(): from samri.fetch.local import summary_atlas mapping='/usr/share/mouse-brain-templates/dsurqe_labels.csv' atlas='/usr/share/mouse-brain-templates/dsurqec_40micron_labels.nii' summary={ 1:{ 'structure':'Hippocampus', 'summarize':['CA'], 'laterality':'right', }, 2:{ 'structure':'Hippocampus', 'summarize':['CA'], 'laterality':'left', }, 3:{ 'structure':'Cortex', 'summarize':['cortex'], 'laterality':'right', }, 4:{ 'structure':'Cortex', 'summarize':['cortex'], 'laterality':'left', }, } new_atlas, new_mapping = summary_atlas(atlas,mapping, summary=summary, ) new_atlas_data = new_atlas.get_data() output_labels = np.unique(new_atlas_data).tolist() target_labels = [0,] target_labels.extend([i for i in summary.keys()]) assert output_labels == target_labels def test_roi_from_atlaslabel(): from samri.fetch.local import roi_from_atlaslabel mapping='/usr/share/mouse-brain-templates/dsurqe_labels.csv' atlas='/usr/share/mouse-brain-templates/dsurqec_40micron_labels.nii' my_roi = roi_from_atlaslabel(atlas, mapping=mapping, label_names=['cortex'], ) roi_data = my_roi.get_data() output_labels = np.unique(roi_data).tolist() assert output_labels == [0, 1] my_roi = roi_from_atlaslabel(atlas, mapping=mapping, label_names=['cortex'], output_label=3, ) roi_data = my_roi.get_data() output_labels = np.unique(roi_data).tolist() assert output_labels == [0, 3]
from samri.fetch.local import prepare_feature_map prepare_feature_map('/usr/share/ABI-connectivity-data/Ventral_tegmental_area-127651139/', invert_lr=True, save_as='/var/tmp/samri_testing/pytest/vta_127651139.nii.gz', )
identifier_body
test_local.py
import numpy as np def test_prepare_abi_connectivity_maps(): from samri.fetch.local import prepare_abi_connectivity_maps prepare_abi_connectivity_maps('Ventral_tegmental_area', invert_lr_experiments=[ "127651139", "127796728", "127798146", "127867804", "156314762", "160539283", "160540751", "165975096", "166054222", "171021829", "175736945", "278178382", "292958638", "301062306", "304337288", ], ) def test_prepare_feature_map(): from samri.fetch.local import prepare_feature_map prepare_feature_map('/usr/share/ABI-connectivity-data/Ventral_tegmental_area-127651139/', invert_lr=True,
mapping='/usr/share/mouse-brain-templates/dsurqe_labels.csv' atlas='/usr/share/mouse-brain-templates/dsurqec_40micron_labels.nii' summary={ 1:{ 'structure':'Hippocampus', 'summarize':['CA'], 'laterality':'right', }, 2:{ 'structure':'Hippocampus', 'summarize':['CA'], 'laterality':'left', }, 3:{ 'structure':'Cortex', 'summarize':['cortex'], 'laterality':'right', }, 4:{ 'structure':'Cortex', 'summarize':['cortex'], 'laterality':'left', }, } new_atlas, new_mapping = summary_atlas(atlas,mapping, summary=summary, ) new_atlas_data = new_atlas.get_data() output_labels = np.unique(new_atlas_data).tolist() target_labels = [0,] target_labels.extend([i for i in summary.keys()]) assert output_labels == target_labels def test_roi_from_atlaslabel(): from samri.fetch.local import roi_from_atlaslabel mapping='/usr/share/mouse-brain-templates/dsurqe_labels.csv' atlas='/usr/share/mouse-brain-templates/dsurqec_40micron_labels.nii' my_roi = roi_from_atlaslabel(atlas, mapping=mapping, label_names=['cortex'], ) roi_data = my_roi.get_data() output_labels = np.unique(roi_data).tolist() assert output_labels == [0, 1] my_roi = roi_from_atlaslabel(atlas, mapping=mapping, label_names=['cortex'], output_label=3, ) roi_data = my_roi.get_data() output_labels = np.unique(roi_data).tolist() assert output_labels == [0, 3]
save_as='/var/tmp/samri_testing/pytest/vta_127651139.nii.gz', ) def test_summary_atlas(): from samri.fetch.local import summary_atlas
random_line_split
test_local.py
import numpy as np def test_prepare_abi_connectivity_maps(): from samri.fetch.local import prepare_abi_connectivity_maps prepare_abi_connectivity_maps('Ventral_tegmental_area', invert_lr_experiments=[ "127651139", "127796728", "127798146", "127867804", "156314762", "160539283", "160540751", "165975096", "166054222", "171021829", "175736945", "278178382", "292958638", "301062306", "304337288", ], ) def test_prepare_feature_map(): from samri.fetch.local import prepare_feature_map prepare_feature_map('/usr/share/ABI-connectivity-data/Ventral_tegmental_area-127651139/', invert_lr=True, save_as='/var/tmp/samri_testing/pytest/vta_127651139.nii.gz', ) def test_summary_atlas(): from samri.fetch.local import summary_atlas mapping='/usr/share/mouse-brain-templates/dsurqe_labels.csv' atlas='/usr/share/mouse-brain-templates/dsurqec_40micron_labels.nii' summary={ 1:{ 'structure':'Hippocampus', 'summarize':['CA'], 'laterality':'right', }, 2:{ 'structure':'Hippocampus', 'summarize':['CA'], 'laterality':'left', }, 3:{ 'structure':'Cortex', 'summarize':['cortex'], 'laterality':'right', }, 4:{ 'structure':'Cortex', 'summarize':['cortex'], 'laterality':'left', }, } new_atlas, new_mapping = summary_atlas(atlas,mapping, summary=summary, ) new_atlas_data = new_atlas.get_data() output_labels = np.unique(new_atlas_data).tolist() target_labels = [0,] target_labels.extend([i for i in summary.keys()]) assert output_labels == target_labels def
(): from samri.fetch.local import roi_from_atlaslabel mapping='/usr/share/mouse-brain-templates/dsurqe_labels.csv' atlas='/usr/share/mouse-brain-templates/dsurqec_40micron_labels.nii' my_roi = roi_from_atlaslabel(atlas, mapping=mapping, label_names=['cortex'], ) roi_data = my_roi.get_data() output_labels = np.unique(roi_data).tolist() assert output_labels == [0, 1] my_roi = roi_from_atlaslabel(atlas, mapping=mapping, label_names=['cortex'], output_label=3, ) roi_data = my_roi.get_data() output_labels = np.unique(roi_data).tolist() assert output_labels == [0, 3]
test_roi_from_atlaslabel
identifier_name
test_gamma.py
from pytest import approx, raises from fastats.maths.gamma import gammaln def test_gamma_ints(): assert gammaln(10) == approx(12.801827480081469, rel=1e-6) assert gammaln(5) == approx(3.1780538303479458, rel=1e-6) assert gammaln(19) == approx(36.39544520803305, rel=1e-6) def test_gamma_floats(): assert gammaln(3.141) == approx(0.8271155090776673, rel=1e-6) assert gammaln(8.8129) == approx(10.206160943471318, rel=1e-6) assert gammaln(12.001) == approx(17.50475055100354, rel=1e-6) assert gammaln(0.007812) == approx(4.847635060148693, rel=1e-6) assert gammaln(86.13) == approx(296.3450079998172, rel=1e-6) def test_gamma_negative(): raises(AssertionError, gammaln, -1) raises(AssertionError, gammaln, -0.023) raises(AssertionError, gammaln, -10.9)
pytest.main([__file__])
if __name__ == '__main__': import pytest
random_line_split
test_gamma.py
from pytest import approx, raises from fastats.maths.gamma import gammaln def test_gamma_ints(): assert gammaln(10) == approx(12.801827480081469, rel=1e-6) assert gammaln(5) == approx(3.1780538303479458, rel=1e-6) assert gammaln(19) == approx(36.39544520803305, rel=1e-6) def test_gamma_floats(): assert gammaln(3.141) == approx(0.8271155090776673, rel=1e-6) assert gammaln(8.8129) == approx(10.206160943471318, rel=1e-6) assert gammaln(12.001) == approx(17.50475055100354, rel=1e-6) assert gammaln(0.007812) == approx(4.847635060148693, rel=1e-6) assert gammaln(86.13) == approx(296.3450079998172, rel=1e-6) def test_gamma_negative():
if __name__ == '__main__': import pytest pytest.main([__file__])
raises(AssertionError, gammaln, -1) raises(AssertionError, gammaln, -0.023) raises(AssertionError, gammaln, -10.9)
identifier_body
test_gamma.py
from pytest import approx, raises from fastats.maths.gamma import gammaln def test_gamma_ints(): assert gammaln(10) == approx(12.801827480081469, rel=1e-6) assert gammaln(5) == approx(3.1780538303479458, rel=1e-6) assert gammaln(19) == approx(36.39544520803305, rel=1e-6) def test_gamma_floats(): assert gammaln(3.141) == approx(0.8271155090776673, rel=1e-6) assert gammaln(8.8129) == approx(10.206160943471318, rel=1e-6) assert gammaln(12.001) == approx(17.50475055100354, rel=1e-6) assert gammaln(0.007812) == approx(4.847635060148693, rel=1e-6) assert gammaln(86.13) == approx(296.3450079998172, rel=1e-6) def test_gamma_negative(): raises(AssertionError, gammaln, -1) raises(AssertionError, gammaln, -0.023) raises(AssertionError, gammaln, -10.9) if __name__ == '__main__':
import pytest pytest.main([__file__])
conditional_block
test_gamma.py
from pytest import approx, raises from fastats.maths.gamma import gammaln def
(): assert gammaln(10) == approx(12.801827480081469, rel=1e-6) assert gammaln(5) == approx(3.1780538303479458, rel=1e-6) assert gammaln(19) == approx(36.39544520803305, rel=1e-6) def test_gamma_floats(): assert gammaln(3.141) == approx(0.8271155090776673, rel=1e-6) assert gammaln(8.8129) == approx(10.206160943471318, rel=1e-6) assert gammaln(12.001) == approx(17.50475055100354, rel=1e-6) assert gammaln(0.007812) == approx(4.847635060148693, rel=1e-6) assert gammaln(86.13) == approx(296.3450079998172, rel=1e-6) def test_gamma_negative(): raises(AssertionError, gammaln, -1) raises(AssertionError, gammaln, -0.023) raises(AssertionError, gammaln, -10.9) if __name__ == '__main__': import pytest pytest.main([__file__])
test_gamma_ints
identifier_name