file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
lib.rs
#![feature(unboxed_closures)] extern crate libc; macro_rules! assert_enum { (@as_expr $e:expr) => {$e}; (@as_pat $p:pat) => {$p}; ($left:expr, $($right:tt)*) => ( { match &($left) { assert_enum!(@as_pat &$($right)*(..)) => {}, _ => { ...
pub use context::*; pub use collections::*; pub use value::*; pub use borrow::*; pub use function::*; pub struct nil; #[macro_export] macro_rules! push { ($cxt:expr, $($arg:expr),*) => ( $( $cxt.push($arg); )* ) }
mod borrow; mod function;
random_line_split
issue-50706.rs
// Copyright 2018 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 ...
match stat { Stats::A => Some(Stats::A), _ => None, } } } fn main() {}
random_line_split
issue-50706.rs
// Copyright 2018 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 ...
; #[derive(PartialEq, Eq)] pub struct StatVariant { pub id: u8, _priv: (), } #[derive(PartialEq, Eq)] pub struct Stat { pub variant: StatVariant, pub index: usize, _priv: (), } impl Stats { pub const TEST: StatVariant = StatVariant{id: 0, _priv: (),}; #[allow(non_upper_case_globals)] ...
Stats
identifier_name
hg-to-git.py
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, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRAN...
#------------------------------------------------------------------------------ def getgitenv(user, date): env = '' elems = re.compile('(.*?)\s+<(.*)>').match(user) if elems: env += 'export GIT_AUTHOR_NAME="%s" ;' % elems.group(1) env += 'export GIT_COMMITTER_NAME="%s" ;' % elems.group(1)...
print """\ %s: [OPTIONS] <hgprj> options: -s, --gitstate=FILE: name of the state to be saved/read for incrementals -n, --nrepack=INT: number of changesets that will trigger a repack (default=0, -1 to deactivate) -v, --verbose: be verbose required: ...
identifier_body
hg-to-git.py
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, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRAN...
else: # Normal changesets # For first children, take the parent branch, for the others create a new branch if hgchildren[parent][0] == str(cset): hgbranch[str(cset)] = hgbranch[parent] else: hgbranch[str(cset)] = "branch-" + str(cset) if not hgvers.has_key("...
hgbranch[str(cset)] = hgbranch[parent]
conditional_block
hg-to-git.py
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, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRAN...
(user, date): env = '' elems = re.compile('(.*?)\s+<(.*)>').match(user) if elems: env += 'export GIT_AUTHOR_NAME="%s" ;' % elems.group(1) env += 'export GIT_COMMITTER_NAME="%s" ;' % elems.group(1) env += 'export GIT_AUTHOR_EMAIL="%s" ;' % elems.group(2) env += 'export GIT_COM...
getgitenv
identifier_name
hg-to-git.py
""" hg-to-git.py - A Mercurial to GIT converter Copyright (C)2007 Stelian Pop <stelian@popies.net> 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, or (at your opti...
random_line_split
webpack.base.babel.js
/** * COMMON WEBPACK CONFIGURATION */ const path = require('path'); const webpack = require('webpack'); module.exports = (options) => ({ entry: options.entry, output: Object.assign({ // Compile into js/build.js path: path.resolve(process.cwd(), 'build'), publicPath: '/', }, options.output), // Merge w...
modules: ['app', 'node_modules'], extensions: [ '.js', '.jsx', '.react.js', ], mainFields: [ 'browser', 'jsnext:main', 'main', ], }, devtool: options.devtool, target: 'web', // Make web variables accessible to webpack, e.g. window });
new webpack.NamedModulesPlugin(), ]), resolve: {
random_line_split
llms-form-checkout.js
this.$form_sections = this.$confirm_form.find( '.llms-checkout-section' ); this.$confirm_form.on( 'submit', function() { self.processing( 'start' ); } ); } }; /** * Public function which allows other classes or extensions to add * before submit events to llms checkout private "before_subm...
} } ); } ); // enable / disable buttons depending on field validation status $( '.llms-payment-gateways' ).on( 'llms-gateway-selected', function( e, data ) { var $submit = $( '#llms_create_pending_order' ); if ( data.$selector && data.$selector.find( '.llms-gateway-fields .invalid' ).len...
} else { // disable fields $fields.attr( 'disabled', 'disabled' );
random_line_split
llms-form-checkout.js
ms-checkout-wrapper' ).prepend( $err ); } $err.append( '<li>' + message + '</li>' ); if ( data ) { console.error( data ); } }; /** * Public function which allows other classes or extensions to add * gateways classes that should be bound by this class * * @param obj gateway_class...
{ var g = gateways[i]; if ( typeof g === 'object' && g !== null ) { if ( g.bind !== undefined && 'function' === typeof g.bind ) { g.bind(); } } }
conditional_block
main.rs
#![cfg_attr(feature = "nightly-testing", feature(plugin))] #![cfg_attr(feature = "nightly-testing", plugin(clippy))] #[macro_use] extern crate clap; extern crate hoedown; extern crate rayon; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate toml; extern crate inflector; ...
if let Some(matches) = matches.subcommand_matches("generate") { let services_config_path = matches.value_of("services_config").unwrap(); let service_configs = ServiceConfig::load_all(services_config_path).expect("Unable to read services configuration file."); let out_dir = Path::new(match...
{ let services_config_path = matches.value_of("services_config").unwrap(); let service_configs = ServiceConfig::load_all(services_config_path).expect("Unable to read services configuration file."); commands::check::check(service_configs); }
conditional_block
main.rs
#![cfg_attr(feature = "nightly-testing", feature(plugin))] #![cfg_attr(feature = "nightly-testing", plugin(clippy))] #[macro_use] extern crate clap; extern crate hoedown; extern crate rayon; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate toml; extern crate inflector; ...
use clap::{Arg, App, SubCommand}; use service::Service; use config::ServiceConfig; use botocore::ServiceDefinition; fn main() { let matches = App::new("Rusoto Service Crate Generator") .version(crate_version!()) .author(crate_authors!()) .about(crate_description!()) .subcommand(Sub...
mod util; mod doco; use std::path::Path;
random_line_split
main.rs
#![cfg_attr(feature = "nightly-testing", feature(plugin))] #![cfg_attr(feature = "nightly-testing", plugin(clippy))] #[macro_use] extern crate clap; extern crate hoedown; extern crate rayon; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate toml; extern crate inflector; ...
.get_matches(); if let Some(matches) = matches.subcommand_matches("check") { let services_config_path = matches.value_of("services_config").unwrap(); let service_configs = ServiceConfig::load_all(services_config_path).expect("Unable to read services configuration file."); commands:...
{ let matches = App::new("Rusoto Service Crate Generator") .version(crate_version!()) .author(crate_authors!()) .about(crate_description!()) .subcommand(SubCommand::with_name("check") .arg(Arg::with_name("services_config") .long("config") ....
identifier_body
main.rs
#![cfg_attr(feature = "nightly-testing", feature(plugin))] #![cfg_attr(feature = "nightly-testing", plugin(clippy))] #[macro_use] extern crate clap; extern crate hoedown; extern crate rayon; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate toml; extern crate inflector; ...
() { let matches = App::new("Rusoto Service Crate Generator") .version(crate_version!()) .author(crate_authors!()) .about(crate_description!()) .subcommand(SubCommand::with_name("check") .arg(Arg::with_name("services_config") .long("config") ...
main
identifier_name
ServicesPanel.spec.tsx
/// <reference types='jest' /> import * as React from 'react'; import ServicesPanel from '../ServicesPanel'; import Cases from './ServicesPanel.cases'; import { shallow, mount, render } from 'enzyme'; describe('ServicesPanel', () => { let servicesPanel:any; beforeEach(()=>{ servicesPanel = mount(<ServicesP...
// return value === true; // }); // expect(allHaveActiveRole).toEqual(true); }); it('should render only services with the selected role when a search value is entered by user', () => { // let activeRole = 'Mollis.'; // servicesPanel.setState({ // activeRole: activeRole, // searh...
// let allHaveActiveRole = servicesPanel.find('ServiceCard').map((node:any) => { // return node.props().service.roles.indexOf(activeRole) > -1; // }).every((value:boolean) => {
random_line_split
DateArrayType.js
/*! * Module dependencies. */ var util = require('util'), moment = require('moment'), super_ = require('../Type'); /** * Date FieldType Constructor * @extends Field * @api public */ function datearray(list, path, options) { this._nativeType = [Date]; this._defaultSize = 'medium'; this._underscoreMethods...
if (Array.isArray(value)) { // Only save valid dates value = value.filter(function(date) { return moment(date).isValid(); }); } if (value === null) { value = []; } if ('string' === typeof value) { if (moment(value).isValid()) { value = [value]; } } if (Array.isArray(value)) { ...
random_line_split
DateArrayType.js
/*! * Module dependencies. */ var util = require('util'), moment = require('moment'), super_ = require('../Type'); /** * Date FieldType Constructor * @extends Field * @api public */ function datearray(list, path, options) { this._nativeType = [Date]; this._defaultSize = 'medium'; this._underscoreMethods...
} if (Array.isArray(value)) { item.set(this.path, value); } } else item.set(this.path, []); process.nextTick(callback); }; /*! * Export class */ module.exports = datearray;
{ value = [value]; }
conditional_block
DateArrayType.js
/*! * Module dependencies. */ var util = require('util'), moment = require('moment'), super_ = require('../Type'); /** * Date FieldType Constructor * @extends Field * @api public */ function datearray(list, path, options)
/*! * Inherit from Field */ util.inherits(datearray, super_); /** * Formats the field value * * @api public */ datearray.prototype.format = function(item, format) { if (format || this.formatString) { return item.get(this.path) ? moment(item.get(this.path)).format(format || this.formatString) : ''; } else...
{ this._nativeType = [Date]; this._defaultSize = 'medium'; this._underscoreMethods = ['format']; this._properties = ['formatString']; this.parseFormatString = options.parseFormat || 'YYYY-MM-DD'; this.formatString = (options.format === false) ? false : (options.format || 'Do MMM YYYY'); if (this.formatStrin...
identifier_body
DateArrayType.js
/*! * Module dependencies. */ var util = require('util'), moment = require('moment'), super_ = require('../Type'); /** * Date FieldType Constructor * @extends Field * @api public */ function
(list, path, options) { this._nativeType = [Date]; this._defaultSize = 'medium'; this._underscoreMethods = ['format']; this._properties = ['formatString']; this.parseFormatString = options.parseFormat || 'YYYY-MM-DD'; this.formatString = (options.format === false) ? false : (options.format || 'Do MMM YYYY'); ...
datearray
identifier_name
TestClz.rs
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by app...
} int2 __attribute__((kernel)) testClzInt2Int2(int2 inValue) { return clz(inValue); } int3 __attribute__((kernel)) testClzInt3Int3(int3 inValue) { return clz(inValue); } int4 __attribute__((kernel)) testClzInt4Int4(int4 inValue) { return clz(inValue); } uint __attribute__((kernel)) testClzUintUint(uint ...
return clz(inValue); } int __attribute__((kernel)) testClzIntInt(int inValue) { return clz(inValue);
random_line_split
pagination.ts
import { Next, Request, Response } from "restify"; export interface PaginationMiddlewareConfig { perPage?: number; count: number; } export interface PaginatedResponse extends Response { sendPaginatedResponse(status?: any, body?: any, headers?: { [header: string]: string }): any; } export interface Pagina...
res.setHeader("link", link); res.send(code, object, headers); }; next(); }; } }
{ link.push("<" + baseUrl + "?page=1&per_page=" + perPage + '>; rel="first"'); link.push("<" + baseUrl + "?page=" + (page - 1) + "&per_page=" + perPage + '>; rel="prev"'); }
conditional_block
pagination.ts
import { Next, Request, Response } from "restify"; export interface PaginationMiddlewareConfig { perPage?: number; count: number; } export interface PaginatedResponse extends Response { sendPaginatedResponse(status?: any, body?: any, headers?: { [header: string]: string }): any; } export interface Pagina...
link.push("<" + baseUrl + "?page=" + (page + 1) + "&per_page=" + perPage + '>; rel="next"'); link.push("<" + baseUrl + "?page=" + lastPage + "&per_page=" + perPage + '>; rel="last"'); } // If we are not on the first page, display the first page ...
const lastPage = config.count / perPage; // If we are not on the last page, display the last page and next if (page < lastPage) {
random_line_split
pagination.ts
import { Next, Request, Response } from "restify"; export interface PaginationMiddlewareConfig { perPage?: number; count: number; } export interface PaginatedResponse extends Response { sendPaginatedResponse(status?: any, body?: any, headers?: { [header: string]: string }): any; } export interface Pagina...
(config: PaginationMiddlewareConfig) { if (config.perPage === undefined) { config.perPage = 30; } return (req: PaginatedRequest, res: PaginatedResponse, next: Next) => { const page = (req.query.page !== undefined) ? Number(req.query.page) : 1; const perPage =...
handlePagination
identifier_name
object-util.d.ts
/** * Sets the value of a field. * * @param {Object} obj The object * @param {string} field The path to a field. Can include dots (.) * @param {*} val The value to set the field * @return {Object} The modified object */ export function setFieldValue(obj: any, field: ...
*/ export function pick(obj: any, fields: string[], options?: { excludeUndefinedValues: boolean; }): any; /** * Determines if embedded document. * * @param {Model} doc The Mongoose document * @return {boolean} True if embedded document, False otherwise. */ export function isEmbedded...
* @return {Object} An object containing only those fields that have been picked
random_line_split
type_variable.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
* dir, vid1)` where `vid1` is some other variable id. */ let old_value = { let value_ptr = &mut self.values.get_mut(vid.index).value; mem::replace(value_ptr, Known(ty)) }; let relations = match old_value { Bounded(b) => b, Known...
* Instantiates `vid` with the type `ty` and then pushes an * entry onto `stack` for each of the relations of `vid` to * other variables. The relations will have the form `(ty,
random_line_split
type_variable.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn replace_if_possible(&self, t: Ty<'tcx>) -> Ty<'tcx> { match t.sty { ty::ty_infer(ty::TyVar(v)) => { match self.probe(v) { None => t, Some(u) => u } } _ => t, } } pub fn snaps...
{ match self.values.get(vid.index).value { Bounded(..) => None, Known(t) => Some(t) } }
identifier_body
type_variable.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&mut self) -> Snapshot { Snapshot { snapshot: self.values.start_snapshot() } } pub fn rollback_to(&mut self, s: Snapshot) { self.values.rollback_to(s.snapshot); } pub fn commit(&mut self, s: Snapshot) { self.values.commit(s.snapshot); } } impl<'tcx> sv::SnapshotVecDelegat...
snapshot
identifier_name
domparser.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::DOMParserBinding; use dom::bindings::codegen::DOMParserBinding::SupportedTypeValues::{...
unreachable!(); } fn GetParentObject(&self, _cx: *JSContext) -> Option<@mut Reflectable> { Some(self.owner as @mut Reflectable) } }
&mut self.reflector_ } fn wrap_object_shared(@mut self, _cx: *JSContext, _scope: *JSObject) -> *JSObject {
random_line_split
domparser.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::DOMParserBinding; use dom::bindings::codegen::DOMParserBinding::SupportedTypeValues::{...
Text_xml => { AbstractDocument::as_abstract(cx, @mut Document::new(self.owner, XML)) } _ => { fail!("unsupported document type") } }; let root = @HTMLHtmlElement { htmlelement: HTMLElement::new(HTMLHtmlElementT...
{ HTMLDocument::new(self.owner) }
conditional_block
domparser.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::DOMParserBinding; use dom::bindings::codegen::DOMParserBinding::SupportedTypeValues::{...
pub fn new(owner: @mut Window) -> @mut DOMParser { reflect_dom_object(@mut DOMParser::new_inherited(owner), owner, DOMParserBinding::Wrap) } pub fn Constructor(owner: @mut Window) -> Fallible<@mut DOMParser> { Ok(DOMParser::new(owner)) } pub fn ParseFro...
{ DOMParser { owner: owner, reflector_: Reflector::new() } }
identifier_body
domparser.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::DOMParserBinding; use dom::bindings::codegen::DOMParserBinding::SupportedTypeValues::{...
(&self, _cx: *JSContext) -> Option<@mut Reflectable> { Some(self.owner as @mut Reflectable) } }
GetParentObject
identifier_name
validation.js
/** * External dependencies */
compact, inRange, isArray, isEmpty } from 'lodash'; import i18n from 'i18n-calypso'; function creditCardFieldRules() { return { name: { description: i18n.translate( 'Name on Card', { context: 'Upgrades: Card holder name label on credit card form', textOnly: true } ), rules: [ 'required' ] }, ...
import creditcards from 'creditcards'; import { capitalize,
random_line_split
validation.js
/** * External dependencies */ import creditcards from 'creditcards'; import { capitalize, compact, inRange, isArray, isEmpty } from 'lodash'; import i18n from 'i18n-calypso'; function creditCardFieldRules() { return { name: { description: i18n.translate( 'Name on Card', { context: 'Upgrades: Card hol...
( cardDetails ) { const rules = creditCardFieldRules(), errors = Object.keys( rules ).reduce( function( allErrors, fieldName ) { const field = rules[ fieldName ], newErrors = getErrors( field, cardDetails[ fieldName ], cardDetails ); if ( newErrors.length ) { allErrors[ fieldName ] = newErrors; } ...
validateCardDetails
identifier_name
validation.js
/** * External dependencies */ import creditcards from 'creditcards'; import { capitalize, compact, inRange, isArray, isEmpty } from 'lodash'; import i18n from 'i18n-calypso'; function creditCardFieldRules() { return { name: { description: i18n.translate( 'Name on Card', { context: 'Upgrades: Card hol...
return null; } function getErrors( field, value, cardDetails ) { return compact( field.rules.map( function( rule ) { const validator = getValidator( rule ); if ( ! validator.isValid( value, cardDetails ) ) { return validator.error( field.description ); } } ) ); } function getValidator( rule ) { if ( is...
{ if ( number ) { number = number.replace( / /g, '' ); if ( number.match( /^3[47]\d{0,13}$/ ) ) { return 'amex'; } else if ( number.match( /^4\d{0,12}$/ ) || number.match( /^4\d{15}$/ ) ) { return 'visa'; } else if ( number.match( /^5[1-5]\d{0,14}$/ ) ) { return 'mastercard'; } else if ( number....
identifier_body
validation.js
/** * External dependencies */ import creditcards from 'creditcards'; import { capitalize, compact, inRange, isArray, isEmpty } from 'lodash'; import i18n from 'i18n-calypso'; function creditCardFieldRules() { return { name: { description: i18n.translate( 'Name on Card', { context: 'Upgrades: Card hol...
return validationResult[ property ]; } ); }, error: function( description ) { return i18n.translate( '%(description)s is invalid', { args: { description: capitalize( description ) } } ); } }; } function validateCardDetails( cardDetails ) { const rules = creditCardFieldRules(), errors = Ob...
{ return ! validationResult.expired; }
conditional_block
IDMappingGridContainer.js
define([ 'dojo/_base/declare', 'dojo/_base/lang', 'dojo/on', 'dojo/topic', 'dijit/popup', 'dijit/TooltipDialog', './IDMappingGrid', './GridContainer' ], function ( declare, lang, on, Topic, popup, TooltipDialog, IDMappingGrid, GridContainer ) { return declare([GridContainer], { gridCtor: IDMappingGri...
if (this.grid) { this.grid.set('state', state); } else { // console.log("No Grid Yet (IDMappingGridContainer)"); } this._set('state', state); } }); });
{ return; }
conditional_block
IDMappingGridContainer.js
define([ 'dojo/_base/declare', 'dojo/_base/lang', 'dojo/on', 'dojo/topic',
declare, lang, on, Topic, popup, TooltipDialog, IDMappingGrid, GridContainer ) { return declare([GridContainer], { gridCtor: IDMappingGrid, containerType: 'feature_data', facetFields: [], enableFilterPanel: false, buildQuery: function () { // prevent further filtering. DO NOT DELETE ...
'dijit/popup', 'dijit/TooltipDialog', './IDMappingGrid', './GridContainer' ], function (
random_line_split
coercion.rs
value // provided is `expr`, we will be adding an implicit borrow, // meaning that we convert `f(expr)` to `f(&M *expr)`. Therefore, // to type check, we will construct the type that `&M*expr` would // yield. match a.sty { ty::ty_rptr(_, mt_a) => { ...
coerce_unsafe_ptr
identifier_name
coercion.rs
coercions occur. use check::{autoderef, FnCtxt, NoPreference, PreferMutLvalue, UnresolvedTypeAction}; use middle::infer::{self, Coercion}; use middle::traits::{self, ObligationCause}; use middle::traits::{predicate_for_trait_def, report_selection_error}; use middle::ty::{AutoDerefRef, AdjustDerefRef}; use middle::ty...
self.coerce_unsized(a, b) }); if unsize.is_ok() { return unsize; } // Examine the supertype and consider auto-borrowing. // // Note: does not attempt to resolve type variables we encounter. // See above for details. match b.sty { ...
a.repr(self.tcx()), b.repr(self.tcx())); // Consider coercing the subtype to a DST let unsize = self.unpack_actual_value(a, |a| {
random_line_split
coercion.rs
ions occur. use check::{autoderef, FnCtxt, NoPreference, PreferMutLvalue, UnresolvedTypeAction}; use middle::infer::{self, Coercion}; use middle::traits::{self, ObligationCause}; use middle::traits::{predicate_for_trait_def, report_selection_error}; use middle::ty::{AutoDerefRef, AdjustDerefRef}; use middle::ty::{sel...
let (source, reborrow) = match (&source.sty, &target.sty) { (&ty::ty_rptr(_, mt_a), &ty::ty_rptr(_, mt_b)) => { try!(coerce_mutbls(mt_a.mutbl, mt_b.mutbl)); let coercion = Coercion(self.origin.span()); let r_borrow = self.fcx.infcx().next_region_var(c...
{ debug!("coerce_unsized(source={}, target={})", source.repr(self.tcx()), target.repr(self.tcx())); let traits = (self.tcx().lang_items.unsize_trait(), self.tcx().lang_items.coerce_unsized_trait()); let (unsize_did, coerce_unsized_did) = if le...
identifier_body
main.py
from flask import Blueprint, render_template, redirect, url_for, current_app monitoring_main = Blueprint('monitoring_main', __name__, # pylint: disable=invalid-name template_folder='templates', static_url_path='/static',
def inject_data(): data = { 'dashboards': current_app.config['monitoring']['dashboards'], 'uchiwa_url': current_app.config['monitoring']['uchiwa_url'], } return data @monitoring_main.route('/') def index(): return redirect(url_for('monitoring_main.events')) @monitoring_main.route('/e...
static_folder='static') @monitoring_main.context_processor
random_line_split
main.py
from flask import Blueprint, render_template, redirect, url_for, current_app monitoring_main = Blueprint('monitoring_main', __name__, # pylint: disable=invalid-name template_folder='templates', static_url_path='/static', static_folde...
@monitoring_main.route('/events') def events(): return render_template('events.html', title='Events') @monitoring_main.route('/checks') def checks(): return render_template('checks.html', title='Checks') @monitoring_main.route('/clients') def clients(): return render_template('clients.html', title='C...
return redirect(url_for('monitoring_main.events'))
identifier_body
main.py
from flask import Blueprint, render_template, redirect, url_for, current_app monitoring_main = Blueprint('monitoring_main', __name__, # pylint: disable=invalid-name template_folder='templates', static_url_path='/static', static_folde...
(): return render_template('checks.html', title='Checks') @monitoring_main.route('/clients') def clients(): return render_template('clients.html', title='Clients') @monitoring_main.route('/clients/<zone>/<client_name>') def client(zone, client_name): return render_template('client_details.html', zone=zo...
checks
identifier_name
test_render.py
""" Tests for content rendering """
import ddt from discussion_api.render import render_body def _add_p_tags(raw_body): """Return raw_body surrounded by p tags""" return "<p>{raw_body}</p>".format(raw_body=raw_body) @ddt.ddt class RenderBodyTest(TestCase): """Tests for render_body""" def test_empty(self): self.assertEqual(ren...
from unittest import TestCase
random_line_split
test_render.py
""" Tests for content rendering """ from unittest import TestCase import ddt from discussion_api.render import render_body def _add_p_tags(raw_body): """Return raw_body surrounded by p tags""" return "<p>{raw_body}</p>".format(raw_body=raw_body) @ddt.ddt class RenderBodyTest(TestCase): """Tests for re...
(self): raw_body = '<img src="gopher://foo">' self.assertEqual(render_body(raw_body), "<p></p>") def test_script_tag(self): raw_body = '<script type="text/javascript">alert("evil script");</script>' self.assertEqual(render_body(raw_body), 'alert("evil script");') @ddt.data("p",...
test_disallowed_img_tag
identifier_name
test_render.py
""" Tests for content rendering """ from unittest import TestCase import ddt from discussion_api.render import render_body def _add_p_tags(raw_body): """Return raw_body surrounded by p tags""" return "<p>{raw_body}</p>".format(raw_body=raw_body) @ddt.ddt class RenderBodyTest(TestCase): """Tests for re...
@ddt.data("http", "https") def test_allowed_img_tag(self, protocol): raw_body = '<img src="{protocol}://foo" width="111" height="222" alt="bar" title="baz">'.format( protocol=protocol ) self.assertEqual(render_body(raw_body), _add_p_tags(raw_body)) def test_disallowed_...
raw_body = '<a href="gopher://foo">link content</a>' self.assertEqual(render_body(raw_body), "<p>link content</p>")
identifier_body
resolve.rs
use std::collections::{HashMap, HashSet}; use core::{Package, PackageId, SourceId}; use core::registry::PackageRegistry; use core::resolver::{self, Resolve, Method}; use ops; use util::CargoResult; /// Resolve all dependencies for the specified `package` using the previous /// lockfile as a guide if present. /// /// ...
let mut resolved = try!(resolver::resolve(&summary, &method, registry)); match previous { Some(r) => resolved.copy_metadata(r), None => {} } return Ok(resolved); fn keep<'a>(p: &&'a PackageId, to_avoid_packages: Option<&HashSet<&'a PackageId>>, to_avo...
random_line_split
resolve.rs
use std::collections::{HashMap, HashSet}; use core::{Package, PackageId, SourceId}; use core::registry::PackageRegistry; use core::resolver::{self, Resolve, Method}; use ops; use util::CargoResult; /// Resolve all dependencies for the specified `package` using the previous /// lockfile as a guide if present. /// /// ...
} } None => {} } let summary = package.summary().clone(); let summary = match previous { Some(r) => { // In the case where a previous instance of resolve is available, we // want to lock as many packages as possible to the previous version ...
{ try!(registry.add_sources(&[package.package_id().source_id() .clone()])); // Here we place an artificial limitation that all non-registry sources // cannot be locked at more than one revision. This means that if a git // repository provides more than one packag...
identifier_body
resolve.rs
use std::collections::{HashMap, HashSet}; use core::{Package, PackageId, SourceId}; use core::registry::PackageRegistry; use core::resolver::{self, Resolve, Method}; use ops; use util::CargoResult; /// Resolve all dependencies for the specified `package` using the previous /// lockfile as a guide if present. /// /// ...
<'a>(registry: &mut PackageRegistry, package: &Package, method: Method, previous: Option<&'a Resolve>, to_avoid: Option<&HashSet<&'a PackageId>>) -> CargoR...
resolve_with_previous
identifier_name
plugin.js
Height = heightCtrl.value(); if (win.find('#constrain')[0].checked() && width && height && newWidth && newHeight) { if (width != newWidth) { newHeight = Math.round((newWidth / width) * newHeight); if (!isNaN(newHeight)) { heightCtrl.value(newHeight); } } else { newWidth ...
this.value(srcURL); getImageSize(editor.documentBaseURI.toAbsolute(this.value()), function(data) { if (data.width && data.height && imageDimensions) { width = data.width; height = data.height; win.find('#width').value(width); win.find('#height').value(height); } ...
{ var srcURL, prependURL, absoluteURLPattern, meta = e.meta || {}; if (imageListCtrl) { imageListCtrl.value(editor.convertURL(this.value(), 'src')); } tinymce.each(meta, function(value, key) { win.find('#' + key).value(value); }); if (!meta.width && !meta.height) { srcURL = ...
identifier_body
plugin.js
(width, height) { if (img.parentNode) { img.parentNode.removeChild(img); } callback({width: width, height: height}); } img.onload = function() { done(img.clientWidth, img.clientHeight); }; img.onerror = function() { done(); }; var style = img.style; style.visibility...
done
identifier_name
plugin.js
newHeight = heightCtrl.value(); if (win.find('#constrain')[0].checked() && width && height && newWidth && newHeight) { if (width != newWidth) { newHeight = Math.round((newWidth / width) * newHeight); if (!isNaN(newHeight)) { heightCtrl.value(newHeight); } } else { newWi...
editor.focus(); editor.nodeChanged(); } return; } if (data.title === "") { data.title = null; } if (!imgElm) { data.id = '__mcenew'; editor.focus(); editor.selection.setContent(dom.createHTML('img', data)); imgElm = dom.get('__mcenew'); ...
if (!data.src) { if (imgElm) { dom.remove(imgElm);
random_line_split
plugin.js
if (!data.style) { data.style = null; } // Setup new data excluding style properties /*eslint dot-notation: 0*/ data = { src: data.src, alt: data.alt, title: data.title, width: data.width, height: data.height, style: data.style, "class": data["class"] }; ...
{ css['border-width'] = addPixelSuffix(data.border); }
conditional_block
transform.py
"""Helper functions for transforming results.""" import hashlib import logging import os import re import urllib.parse from typing import Optional from docutils.core import publish_parts from dump2polarion.exporters.verdicts import Verdicts # pylint: disable=invalid-name logger = logging.getLogger(__name__) TEST_P...
(result): """Make sure that test class is included in "title". Applies only to titles derived from test function names, e.g. "test_power_parent_service" -> "TestServiceRESTAPI.test_power_parent_service" >>> result = {"title": "test_foo", "id": "test_foo", "classname": "foo.bar.baz.TestFoo", ... ...
include_class_in_title
identifier_name
transform.py
"""Helper functions for transforming results.""" import hashlib import logging import os import re import urllib.parse from typing import Optional from docutils.core import publish_parts from dump2polarion.exporters.verdicts import Verdicts # pylint: disable=invalid-name logger = logging.getLogger(__name__) TEST_P...
automation_link = '<a href="{}">Test Source</a>'.format(automation_script) testcase["description"] = "{}<br/>{}".format(testcase.get("description") or "", automation_link) return testcase
return testcase
conditional_block
transform.py
"""Helper functions for transforming results.""" import hashlib import logging import os import re import urllib.parse from typing import Optional from docutils.core import publish_parts from dump2polarion.exporters.verdicts import Verdicts # pylint: disable=invalid-name logger = logging.getLogger(__name__) TEST_P...
'some_id' """ testcase_title = testcase.get("title") testcase_id = testcase.get("id") if not testcase_id or testcase_id.lower().startswith("test"): testcase_id = gen_unique_id("{}{}".format(append_str, testcase_title)) return testcase_id def parse_rst_description(testcase): """Crea...
'5acc5dc795a620c6b4491b681e5da39c' >>> get_testcase_id({"title": "some title", "id": "TestClass.test_name"}, "vmaas_") '2ea7695b73763331f8a0c4aec75362b8' >>> str(get_testcase_id({"title": "some title", "id": "some_id"}, "vmaas_"))
random_line_split
transform.py
"""Helper functions for transforming results.""" import hashlib import logging import os import re import urllib.parse from typing import Optional from docutils.core import publish_parts from dump2polarion.exporters.verdicts import Verdicts # pylint: disable=invalid-name logger = logging.getLogger(__name__) TEST_P...
def parse_rst_description(testcase): """Create an HTML version of the RST formatted description.""" description = testcase.get("description") if not description: return try: with open(os.devnull, "w") as devnull: testcase["description"] = publish_parts( d...
"""Return new test case ID. >>> get_testcase_id({"title": "TestClass.test_name"}, "vmaas_") '5acc5dc795a620c6b4491b681e5da39c' >>> get_testcase_id({"title": "TestClass.test_name", "id": "TestClass.test_name"}, "vmaas_") '5acc5dc795a620c6b4491b681e5da39c' >>> get_testcase_id({"title": "TestClass.tes...
identifier_body
assign-to-method.rs
// Copyright 2012 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 ...
{ meows : usize, how_hungry : isize, } impl cat { pub fn speak(&self) { self.meows += 1_usize; } } fn cat(in_x : usize, in_y : isize) -> cat { cat { meows: in_x, how_hungry: in_y } } fn main() { let nyan : cat = cat(52_usize, 99); nyan.speak = || println!("meow"); //~ ERROR atte...
cat
identifier_name
assign-to-method.rs
// Copyright 2012 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 ...
meows : usize, how_hungry : isize, } impl cat { pub fn speak(&self) { self.meows += 1_usize; } } fn cat(in_x : usize, in_y : isize) -> cat { cat { meows: in_x, how_hungry: in_y } } fn main() { let nyan : cat = cat(52_usize, 99); nyan.speak = || println!("meow"); //~ ERROR attempt...
struct cat {
random_line_split
assign-to-method.rs
// Copyright 2012 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 ...
{ let nyan : cat = cat(52_usize, 99); nyan.speak = || println!("meow"); //~ ERROR attempted to take value of method }
identifier_body
tdbus_upower.py
# -*- coding: utf-8 -*- ''' This module presents a little code to deal with battery status using DBUS and UPower on Linux @author: pkremer ''' import sys import logging from six.moves import filter from functools import partial import six import tdbus # 'constants' UPOWER_NAME = 'org.freedesktop.UPower' UPOWER_DEV...
@tdbus.signal_handler(member='Changed', interface=UPOWER_DEVICE_IFACE) def Changed(self, message): device = message.get_path() if device in self.device_paths: log.debug('signal received: %s, args = %r', message.get_member(), message...
if devices is None or device is None or device in devices: try: observer(self, device, attributes) except (Exception,) as ex: # pylint: disable=W0703 self.unregister_observer(observer) errmsg = "Exception in message dispatch: H...
conditional_block
tdbus_upower.py
# -*- coding: utf-8 -*- ''' This module presents a little code to deal with battery status using DBUS and UPower on Linux @author: pkremer ''' import sys import logging from six.moves import filter from functools import partial import six import tdbus # 'constants' UPOWER_NAME = 'org.freedesktop.UPower' UPOWER_DEV...
(self, observer, devices=None): """ register a listener function Parameters ----------- observer : external listener function events : tuple or list of relevant events (default=None) """ if devices is not None and type(devices) not in (tuple, list): ...
register_observer
identifier_name
tdbus_upower.py
# -*- coding: utf-8 -*- ''' This module presents a little code to deal with battery status using DBUS and UPower on Linux @author: pkremer ''' import sys import logging from six.moves import filter from functools import partial import six import tdbus # 'constants' UPOWER_NAME = 'org.freedesktop.UPower' UPOWER_DEV...
def ibatteries(conn): ''' Utility that returns an generator for rechargeable power devices. :param conn: DBUS system bus connection ''' def is_rechargeable(conn, device): log.debug("testing IsRechargeable for '%s'", device) return uPowerDeviceGet(conn, device, 'IsRechargeable') ...
conn = connect() result = conn.call_method(tdbus.DBUS_PATH_DBUS, 'ListNames', tdbus.DBUS_INTERFACE_DBUS, destination=tdbus.DBUS_SERVICE_DBUS) conn.close() # see if UPower is in the known services: return UPOWER_NAME in (name for name in result....
identifier_body
tdbus_upower.py
# -*- coding: utf-8 -*- ''' This module presents a little code to deal with battery status using DBUS and UPower on Linux @author: pkremer ''' import sys import logging from six.moves import filter from functools import partial import six import tdbus # 'constants' UPOWER_NAME = 'org.freedesktop.UPower' UPOWER_DEV...
destination=tdbus.DBUS_SERVICE_DBUS) conn.close() # see if UPower is in the known services: return UPOWER_NAME in (name for name in result.get_args()[0] if not name.startswith(':')) def ibatteries(conn): ''' Utility that returns an generato...
tdbus.DBUS_INTERFACE_DBUS,
random_line_split
acc_lib.py
# -*- coding: utf-8 -*- """ Acc Lib - Used by account contasis pre account line pre Created: 11 oct 2020 Last up: 29 mar 2021 """ import datetime class AccFuncs: @staticmethod def static_method(): # the static method gets passed nothing return "I am a static method" @classmethod def class_meth...
# Search Orders orders = obj.env['sale.order'].search([ ('state', 'in', ['sale', 'cancel']), ('date_order', '>=', date_begin), ('date_order', '<', date_end), ], order='x_serial_nr asc', #limit=1, ) # Count ...
date_end_dt = datetime.datetime.strptime(date_ex, DATETIME_FORMAT) + datetime.timedelta(hours=24) + datetime.timedelta(hours=5, minutes=0) date_end = date_end_dt.strftime('%Y-%m-%d %H:%M') #print date_end_dt
random_line_split
acc_lib.py
# -*- coding: utf-8 -*- """ Acc Lib - Used by account contasis pre account line pre Created: 11 oct 2020 Last up: 29 mar 2021 """ import datetime class AccFuncs: @staticmethod def static_method(): # the static method gets passed nothing return "I am a static method" @classmethod def class_meth...
# get_net_tax
x = amount / 1.18 net = float("{0:.2f}".format(x)) # Tax x = amount * 0.18 tax = float("{0:.2f}".format(x)) return net, tax
identifier_body
acc_lib.py
# -*- coding: utf-8 -*- """ Acc Lib - Used by account contasis pre account line pre Created: 11 oct 2020 Last up: 29 mar 2021 """ import datetime class AccFuncs: @staticmethod def static_method(): # the static method gets passed nothing return "I am a static method" @classmethod def class_meth...
(cls, date, delta): if date != False: year = int(date.split('-')[0]) if year >= 1900: DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S" DATETIME_FORMAT_sp = "%d/%m/%Y %H:%M" date_field1 = datetime.datetime.strptime(date, DATETIME_FORMAT) date_corr = date_field1 + datetime.timedelta(hours=delta,minutes=0) ...
correct_time
identifier_name
acc_lib.py
# -*- coding: utf-8 -*- """ Acc Lib - Used by account contasis pre account line pre Created: 11 oct 2020 Last up: 29 mar 2021 """ import datetime class AccFuncs: @staticmethod def static_method(): # the static method gets passed nothing return "I am a static method" @classmethod def class_meth...
# correct_time # ----------------------------------------------------- Get Orders Filter ------ # Provides sales between begin date and end date. # Sales and Cancelled also. @classmethod def get_orders_filter(cls, obj, date_bx, date_ex): # Dates #DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S" DATETIME_FORMAT = "...
year = int(date.split('-')[0]) if year >= 1900: DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S" DATETIME_FORMAT_sp = "%d/%m/%Y %H:%M" date_field1 = datetime.datetime.strptime(date, DATETIME_FORMAT) date_corr = date_field1 + datetime.timedelta(hours=delta,minutes=0) date_corr_sp = date_corr.strftime(DATETIM...
conditional_block
PIXISpriteScreen.tsx
import './BeforePIXI'; import { Asset } from 'expo-asset'; import { Platform } from 'expo-modules-core'; import * as PIXI from 'pixi.js'; import { Dimensions } from 'react-native'; import GLWrap from './GLWrap'; export default GLWrap('pixi.js sprite rendering', async (gl) => { const { scale: resolution } = Dimensi...
const sprite = PIXI.Sprite.from(image); app.stage.addChild(sprite); });
{ image = new Image(asset as any); }
conditional_block
PIXISpriteScreen.tsx
import './BeforePIXI'; import { Asset } from 'expo-asset'; import { Platform } from 'expo-modules-core'; import * as PIXI from 'pixi.js'; import { Dimensions } from 'react-native';
export default GLWrap('pixi.js sprite rendering', async (gl) => { const { scale: resolution } = Dimensions.get('window'); const width = gl.drawingBufferWidth / resolution; const height = gl.drawingBufferHeight / resolution; const app = new PIXI.Application({ context: gl, width, height, resolutio...
import GLWrap from './GLWrap';
random_line_split
scan_threshold.py
import logging from pybar.analysis.analyze_raw_data import AnalyzeRawData from pybar.fei4.register_utils import invert_pixel_mask from pybar.fei4_run_base import Fei4RunBase from pybar.fei4.register_utils import scan_loop from pybar.run_manager import RunManager class ThresholdScan(Fei4RunBase): '''Sta...
commands.extend(self.register.get_commands("RunMode")) self.register_utils.send_commands(commands) def scan(self): scan_parameter_range = [0, (2 ** self.register.global_registers['PlsrDAC']['bitlength'])] if self.scan_parameters.PlsrDAC[0]: scan_parameter_range[0...
self.register.set_pixel_register_value('C_High', 0) commands.extend(self.register.get_commands("WrFrontEnd", same_mask_for_all_dc=True, name='C_High'))
conditional_block
scan_threshold.py
import logging from pybar.analysis.analyze_raw_data import AnalyzeRawData from pybar.fei4.register_utils import invert_pixel_mask from pybar.fei4_run_base import Fei4RunBase from pybar.fei4.register_utils import scan_loop from pybar.run_manager import RunManager class ThresholdScan(Fei4RunBase): '''Sta...
scan_loop(self, cal_lvl1_command, repeat_command=self.n_injections, use_delay=True, mask_steps=self.mask_steps, enable_mask_steps=None, enable_double_columns=None, same_mask_for_all_dc=True, fast_dc_loop=True, bol_function=None, eol_function=None, digital_injection=False, enable_shift_masks=self.enable_...
scan_parameter_range = [0, (2 ** self.register.global_registers['PlsrDAC']['bitlength'])] if self.scan_parameters.PlsrDAC[0]: scan_parameter_range[0] = self.scan_parameters.PlsrDAC[0] if self.scan_parameters.PlsrDAC[1]: scan_parameter_range[1] = self.scan_parameters.PlsrDAC[1...
identifier_body
scan_threshold.py
import logging from pybar.analysis.analyze_raw_data import AnalyzeRawData from pybar.fei4.register_utils import invert_pixel_mask from pybar.fei4_run_base import Fei4RunBase from pybar.fei4.register_utils import scan_loop from pybar.run_manager import RunManager class ThresholdScan(Fei4RunBase): '''Sta...
(self): with AnalyzeRawData(raw_data_file=self.output_filename, create_pdf=True) as analyze_raw_data: analyze_raw_data.create_tot_hist = False analyze_raw_data.create_fitted_threshold_hists = True analyze_raw_data.create_threshold_mask = True analyze_raw_data...
analyze
identifier_name
scan_threshold.py
import logging from pybar.analysis.analyze_raw_data import AnalyzeRawData from pybar.fei4.register_utils import invert_pixel_mask from pybar.fei4_run_base import Fei4RunBase from pybar.fei4.register_utils import scan_loop from pybar.run_manager import RunManager class ThresholdScan(Fei4RunBase): '''Sta...
analyze_raw_data.create_tot_hist = False analyze_raw_data.create_fitted_threshold_hists = True analyze_raw_data.create_threshold_mask = True analyze_raw_data.n_injections = 100 analyze_raw_data.interpreter.set_warning_output(False) # so far the data struc...
with AnalyzeRawData(raw_data_file=self.output_filename, create_pdf=True) as analyze_raw_data:
random_line_split
usrp_transmit_path.py
# # Copyright 2009 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at your option) # any later version. #...
def add_options(parser, expert): add_freq_option(parser) usrp_options.add_tx_options(parser) transmit_path.transmit_path.add_options(parser, expert) expert.add_option("", "--tx-freq", type="eng_float", default=None, help="set transmit frequency to FREQ [default=%default]", me...
parser.add_option('-f', '--freq', type="eng_float", action="callback", callback=freq_callback, help="set Tx and/or Rx frequency to FREQ [default=%default]", metavar="FREQ")
conditional_block
usrp_transmit_path.py
# # Copyright 2009 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at your option) # any later version. #...
if not parser.has_option('--freq'): parser.add_option('-f', '--freq', type="eng_float", action="callback", callback=freq_callback, help="set Tx and/or Rx frequency to FREQ [default=%default]", metavar="FREQ") def add_options(pa...
parser.values.rx_freq = value parser.values.tx_freq = value
identifier_body
usrp_transmit_path.py
# # Copyright 2009 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at your option) # any later version. #...
def add_options(parser, expert): add_freq_option(parser) usrp_options.add_tx_options(parser) transmit_path.transmit_path.add_options(parser, expert) expert.add_option("", "--tx-freq", type="eng_float", default=None, help="set transmit frequency to FREQ [default=%default]", meta...
random_line_split
usrp_transmit_path.py
# # Copyright 2009 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at your option) # any later version. #...
(self, modulator_class, options): ''' See below for what options should hold ''' gr.hier_block2.__init__(self, "usrp_transmit_path", gr.io_signature(0, 0, 0), # Input signature gr.io_signature(0, 0, 0)) # Output signature if opti...
__init__
identifier_name
network_usage.rs
use futures::{Future, Stream}; use std::sync::Arc; use tokio_timer::Timer; use tokio_core::reactor::Handle; use component::Component; use error::{Error, Result}; use std::time::Duration; use utils; #[derive(Clone, PartialEq, Copy)] pub enum Scale { Binary, Decimal, } impl Scale { fn base(&self) -> u16 { ...
Scale::Binary => 1024, } } } #[derive(Clone, Copy)] pub enum Direction { Incoming, Outgoing, } pub struct NetworkUsage { pub interface: String, pub direction: Direction, pub scale: Scale, pub percision: u8, pub refresh_frequency: Duration, pub sample_duration: D...
random_line_split
network_usage.rs
use futures::{Future, Stream}; use std::sync::Arc; use tokio_timer::Timer; use tokio_core::reactor::Handle; use component::Component; use error::{Error, Result}; use std::time::Duration; use utils; #[derive(Clone, PartialEq, Copy)] pub enum Scale { Binary, Decimal, } impl Scale { fn base(&self) -> u16 { ...
{ pub interface: String, pub direction: Direction, pub scale: Scale, pub percision: u8, pub refresh_frequency: Duration, pub sample_duration: Duration, } impl Default for NetworkUsage { fn default() -> NetworkUsage { NetworkUsage { interface: "eth0".to_string(), ...
NetworkUsage
identifier_name
network_usage.rs
use futures::{Future, Stream}; use std::sync::Arc; use tokio_timer::Timer; use tokio_core::reactor::Handle; use component::Component; use error::{Error, Result}; use std::time::Duration; use utils; #[derive(Clone, PartialEq, Copy)] pub enum Scale { Binary, Decimal, } impl Scale { fn base(&self) -> u16 { ...
} fn get_prefix(scale: Scale, power: u8) -> &'static str { match (scale, power) { (Scale::Decimal, 0) | (Scale::Binary, 0) => "B/s", (Scale::Decimal, 1) => "kb/s", (Scale::Decimal, 2) => "Mb/s", (Scale::Decimal, 3) => "Gb/s", (Scale::Decimal, 4) => "Tb/s", (Scale::B...
{ NetworkUsage { interface: "eth0".to_string(), direction: Direction::Incoming, scale: Scale::Binary, percision: 3, refresh_frequency: Duration::from_secs(10), sample_duration: Duration::from_secs(1), } }
identifier_body
index.js
= require('./styleParser'); module.exports.trackedControls = require('./tracked-controls'); module.exports.checkHeadsetConnected = function () { warn('`utils.checkHeadsetConnected` has moved to `utils.device.checkHeadsetConnected`'); return device.checkHeadsetConnected(arguments); }; module.exports.isGearVR = fun...
return data; }; /** * Retrieves querystring value. * @param {String} name Name of querystring key. * @return {String} Value */ module
{ if (el.hasAttribute(key)) { data[key] = el.getAttribute(key); } }
identifier_body
index.js
Parser = require('./styleParser'); module.exports.trackedControls = require('./tracked-controls'); module.exports.checkHeadsetConnected = function () { warn('`utils.checkHeadsetConnected` has moved to `utils.device.checkHeadsetConnected`'); return device.checkHeadsetConnected(arguments); }; module.exports.isGearVR...
(key) { if (el.hasAttribute(key)) { data[key] = el.getAttribute(key); } } return data; }; /** * Retrieves querystring value. * @param {String} name Name of querystring key. * @return {String} Value */ module
copyAttribute
identifier_name
index.js
Parser = require('./styleParser'); module.exports.trackedControls = require('./tracked-controls'); module.exports.checkHeadsetConnected = function () { warn('`utils.checkHeadsetConnected` has moved to `utils.device.checkHeadsetConnected`'); return device.checkHeadsetConnected(arguments); }; module.exports.isGearVR...
/** * Splits a string into an array based on a delimiter. * * @param {string=} [str=''] Source string * @param {string=} [delimiter=' '] Delimiter to use * @returns {array} Array of delimited strings */ module.exports.splitString = function (str, delimiter) { if (typeof delimiter =...
};
random_line_split
time-scons.py
this script, and we should be able # to change what we need to in this script and have it affect the build # automatically when the source code is updated, without having to # restart either master or slave. import optparse import os import shutil import subprocess import sys import tempfile import xml.sax.handler ...
""" status = 0 for command in command_list: s = self.run(command, **kw) if s and status == 0: status = s return 0 def get_svn_revisions(branch, revisions=None): """ Fetch the actual SVN revisions for the given branch querying "svn log...
Returns the exit status of the first failed command, or 0 on success.
random_line_split
time-scons.py
this script, and we should be able # to change what we need to in this script and have it affect the build # automatically when the source code is updated, without having to # restart either master or slave. import optparse import os import shutil import subprocess import sys import tempfile import xml.sax.handler ...
(self, dictionary={}): self.subst_dictionary(dictionary) def subst_dictionary(self, dictionary): self._subst_dictionary = dictionary def subst(self, string, dictionary=None): """ Substitutes (via the format operator) the values in the specified dictionary into the speci...
__init__
identifier_name
time-scons.py
this script, and we should be able # to change what we need to in this script and have it affect the build # automatically when the source code is updated, without having to # restart either master or slave. import optparse import os import shutil import subprocess import sys import tempfile import xml.sax.handler ...
command.append(branch) p = subprocess.Popen(command, stdout=subprocess.PIPE) class SVNLogHandler(xml.sax.handler.ContentHandler): def __init__(self): self.revisions = [] def startElement(self, name, attributes): if name == 'logentry': self.revisions....
command.extend(['-r', revisions])
conditional_block
time-scons.py
to # produce consistent timings, even when the rest of the tree is from # an earlier revision that doesn't have these pieces. TimeSCons_pieces = ['QMTest', 'timings', 'runtest.py'] class CommandRunner(object): """ Executor class for commands, including "commands" implemented by Python functions. """ ...
if argv is None: argv = sys.argv parser = optparse.OptionParser(usage=Usage) parser.add_option("--branch", metavar="BRANCH", default="trunk", help="time revision on BRANCH") parser.add_option("--logsdir", metavar="DIR", default='.', help="generate separat...
identifier_body
float_context.rs
right } /// Wrappers around float methods. To avoid allocating data we'll never use, /// destroy the context on modification. pub enum FloatContext { Invalid, Valid(~FloatContextBase) } impl FloatContext { pub fn new(num_floats: uint) -> FloatContext { Valid(~FloatContextBase::new(num_floats)) ...
#[inline(always)] pub fn last_float_pos(&mut self) -> Point2D<Au> { do self.with_base |base| { base.last_float_pos() } } #[inline(always)] pub fn clearance(&self, clear: ClearType) -> Au { do self.with_base |base| { base.clearance(clear) } ...
{ do self.with_base |base| { base.place_between_floats(info) } }
identifier_body
float_context.rs
right } /// Wrappers around float methods. To avoid allocating data we'll never use, /// destroy the context on modification. pub enum FloatContext { Invalid, Valid(~FloatContextBase) } impl FloatContext { pub fn new(num_floats: uint) -> FloatContext { Valid(~FloatContextBase::new(num_floats)) ...
(&self, bounds: &Rect<Au>) -> bool { for float in self.float_data.iter() { match *float{ None => (), Some(data) => { if data.bounds.translate(&self.offset).intersects(bounds) { return true; } ...
collides_with_float
identifier_name
float_context.rs
{ do self.with_mut_base |base| { base.add_float(info); } replace(self, Invalid) } #[inline(always)] pub fn place_between_floats(&self, info: &PlacementInfo) -> Rect<Au> { do self.with_base |base| { base.place_between_floats(info) } } ...
Size2D(info.max_width, Au(max_value))) }, Some(rect) => { assert!(rect.origin.y + rect.size.height != float_y,
random_line_split
b_lanterns.py
import fileinput def
(s): return([ int(x) for x in s.split() ]) # args = [ 'line 1', 'line 2', ... ] def proc_input(args): (n, l) = str_to_int(args[0]) a = tuple(str_to_int(args[1])) return(l, a) def solve(args, verbose=False): (l, a) = proc_input(args) list_a = list(a) list_a.sort() max_dist = max(list_a[0] * 2, (l - list_a[-1])...
str_to_int
identifier_name
b_lanterns.py
import fileinput def str_to_int(s): return([ int(x) for x in s.split() ]) # args = [ 'line 1', 'line 2', ... ] def proc_input(args):
def solve(args, verbose=False): (l, a) = proc_input(args) list_a = list(a) list_a.sort() max_dist = max(list_a[0] * 2, (l - list_a[-1]) * 2) for x in xrange(len(a) - 1): max_dist = max(max_dist, list_a[x + 1] - list_a[x]) if verbose: print max_dist / float(2) return max_dist / float(2) def test(): assert...
(n, l) = str_to_int(args[0]) a = tuple(str_to_int(args[1])) return(l, a)
identifier_body
b_lanterns.py
import fileinput def str_to_int(s): return([ int(x) for x in s.split() ]) # args = [ 'line 1', 'line 2', ... ] def proc_input(args): (n, l) = str_to_int(args[0]) a = tuple(str_to_int(args[1])) return(l, a) def solve(args, verbose=False): (l, a) = proc_input(args) list_a = list(a) list_a.sort() max_dist = max...
assert(solve([ '4 5', '0 1 2 3' ]) == 2.0) assert(solve([ '7 15', '15 5 3 7 9 14 0' ]) == 2.5) if __name__ == '__main__': from sys import argv if argv.pop() == 'test': test() else: solve(list(fileinput.input()), verbose=True)
random_line_split
b_lanterns.py
import fileinput def str_to_int(s): return([ int(x) for x in s.split() ]) # args = [ 'line 1', 'line 2', ... ] def proc_input(args): (n, l) = str_to_int(args[0]) a = tuple(str_to_int(args[1])) return(l, a) def solve(args, verbose=False): (l, a) = proc_input(args) list_a = list(a) list_a.sort() max_dist = max...
solve(list(fileinput.input()), verbose=True)
conditional_block
concurrency.py
import functools import threading from concurrent.futures import ThreadPoolExecutor import traceback NUMBER_OF_THREADS = 100 def unique_step(parallel, numer_of_threads=NUMBER_OF_THREADS): """Shorten the call for calling a function after the other is completed. @serial_step def get(self, url):...
return call_function_when_done return record_call
def call_function_when_done(function): assert callable(function), "{} must be callable. In {}".format(function, parallel) with lock: future = requesting.get(args) if not future: future = executor.submit(parallel, *args) requ...
identifier_body
concurrency.py
import functools import threading from concurrent.futures import ThreadPoolExecutor import traceback NUMBER_OF_THREADS = 100 def unique_step(parallel, numer_of_threads=NUMBER_OF_THREADS): """Shorten the call for calling a function after the other is completed. @serial_step def get(self, url):...
@future.add_done_callback def call_with_result(future): def call_function(): try: function(future.result()) except: traceback.print_exc() executor.submit(call_function) ...
future = executor.submit(parallel, *args) requesting[args] = future @future.add_done_callback def end_with_result(future): with lock: requesting.pop(args)
conditional_block
concurrency.py
import functools import threading from concurrent.futures import ThreadPoolExecutor import traceback NUMBER_OF_THREADS = 100 def unique_step(parallel, numer_of_threads=NUMBER_OF_THREADS): """Shorten the call for calling a function after the other is completed. @serial_step def get(self, url):...
(): try: function(future.result()) except: traceback.print_exc() executor.submit(call_function) return function return call_function_when_done return record_call
call_function
identifier_name
concurrency.py
NUMBER_OF_THREADS = 100 def unique_step(parallel, numer_of_threads=NUMBER_OF_THREADS): """Shorten the call for calling a function after the other is completed. @serial_step def get(self, url): return parallel thing @get(url): def next_step(): p...
import functools import threading from concurrent.futures import ThreadPoolExecutor import traceback
random_line_split
seenShow.js
$( document ).ready(function() { "use strict"; firebase.auth().onAuthStateChanged(firebaseUser =>{ if (firebaseUser){ var rootRef = firebase.database().ref().child("users").child(firebaseUser.uid).child("movies").child("seen"); rootRef.on("child_added", snap =>{ var movieId = snap.child("m...
}); });
random_line_split