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
multi.rs
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 Parity. If not, see <http://www.gnu.org/license...
sets: BTreeMap<BlockNumber, Box<ValidatorSet>>, block_number: RwLock<BlockNumberLookup>, } impl Multi { pub fn new(set_map: BTreeMap<BlockNumber, Box<ValidatorSet>>) -> Self { assert!(set_map.get(&0u64).is_some(), "ValidatorSet has to be specified from block 0."); Multi { sets: set_map, block_number: RwLo...
pub struct Multi {
random_line_split
multi.rs
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 Parity. If not, see <http://www.gnu.org/license...
(&self, header: &Header, call: &Call) -> Result<Vec<u8>, String> { self.correct_set_by_number(0).1.genesis_epoch_data(header, call) } fn is_epoch_end(&self, _first: bool, chain_head: &Header) -> Option<Vec<u8>> { let (set_block, set) = self.correct_set_by_number(chain_head.number()); let first = set_block == c...
genesis_epoch_data
identifier_name
multi.rs
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 Parity. If not, see <http://www.gnu.org/license...
fn count_with_caller(&self, bh: &H256, caller: &Call) -> usize { self.correct_set(BlockId::Hash(*bh)) .map_or_else(usize::max_value, |set| set.count_with_caller(bh, caller)) } fn report_malicious(&self, validator: &Address, set_block: BlockNumber, block: BlockNumber, proof: Bytes) { self.correct_set_by_num...
{ self.correct_set(BlockId::Hash(*bh)) .map_or_else(Default::default, |set| set.get_with_caller(bh, nonce, caller)) }
identifier_body
rlptraits.rs
decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder; } /// Internal helper trait. Implement `Decodable` for custom types. pub trait RlpDecodable: Sized { /// Decode a value from RLP bytes fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder; } /// A view into RLP encoded dat...
/// Apends value to the end of stream, chainable. /// /// ```rust /// extern crate rlp; /// use rlp::*; /// /// fn main () { /// let mut stream = RlpStream::new_list(2); /// stream.append(&"cat").append(&"dog"); /// let out = stream.out(); /// assert_eq!(out, vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd'...
/// Initializes the `Stream` as a list. fn new_list(len: usize) -> Self;
random_line_split
rlptraits.rs
decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder; } /// Internal helper trait. Implement `Decodable` for custom types. pub trait RlpDecodable: Sized { /// Decode a value from RLP bytes fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder; } /// A view into RLP encoded dat...
(&self) -> ElasticArray1024<u8> { let mut s = RlpStream::new(); self.rlp_append(&mut s); s.drain() } } /// Encodable wrapper trait required to handle special case of encoding a &[u8] as string and not as list pub trait RlpEncodable { /// Append a value to the stream fn rlp_append(&self, s: &mut RlpStream); } ...
rlp_bytes
identifier_name
rlptraits.rs
decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder; } /// Internal helper trait. Implement `Decodable` for custom types. pub trait RlpDecodable: Sized { /// Decode a value from RLP bytes fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder; } /// A view into RLP encoded dat...
} /// Encodable wrapper trait required to handle special case of encoding a &[u8] as string and not as list pub trait RlpEncodable { /// Append a value to the stream fn rlp_append(&self, s: &mut RlpStream); } /// RLP encoding stream pub trait Stream: Sized { /// Initializes instance of empty `Stream`. fn new() ...
{ let mut s = RlpStream::new(); self.rlp_append(&mut s); s.drain() }
identifier_body
ScriptLayer.ts
/** * Copyright © 2021 Rémi Pace. * This file is part of Abc-Map. * * Abc-Map is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later vers...
* but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General * Public License along with Abc-Map. If not, see <https://www.gnu.org...
* Abc-Map is distributed in the hope that it will be useful,
random_line_split
ScriptLayer.ts
/** * Copyright © 2021 Rémi Pace. * This file is part of Abc-Map. * * Abc-Map is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later vers...
return this.layer.unwrap(); } }
identifier_body
ScriptLayer.ts
/** * Copyright © 2021 Rémi Pace. * This file is part of Abc-Map. * * Abc-Map is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later vers...
: boolean { return this.layer.isVector(); } public getFeatures(): Feature<Geometry>[] { if (!this.layer.isVector()) { throw new Error(`Layer with name ${this.name} is not a vector layer`); } return this.layer.getSource().getFeatures(); } public unwrap() { return this.layer.unwrap();...
Vector()
identifier_name
ScriptLayer.ts
/** * Copyright © 2021 Rémi Pace. * This file is part of Abc-Map. * * Abc-Map is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later vers...
return this.layer.getSource().getFeatures(); } public unwrap() { return this.layer.unwrap(); } }
throw new Error(`Layer with name ${this.name} is not a vector layer`); }
conditional_block
map3one.rs
use itertools::izip; use mli::{Backward, Forward, Train}; use ndarray::{Array, Array3}; use num_traits::Zero; use std::ops::Add; #[derive(Clone, Debug)] pub struct Map3One<G>(pub G); impl<G> Forward for Map3One<G> where G: Forward, { type Input = Array3<G::Input>; type Internal = Array3<G::Internal>; ...
impl<G> Backward for Map3One<G> where G: Backward, G::TrainDelta: Clone + Add + Zero, { type OutputDelta = Array3<G::OutputDelta>; type InputDelta = Array3<G::InputDelta>; type TrainDelta = G::TrainDelta; fn backward( &self, input: &Self::Input, internal: &Self::Interna...
let output_array = Array::from_shape_vec(input.raw_dim(), output_vec).unwrap(); (internal_array, output_array) } }
random_line_split
map3one.rs
use itertools::izip; use mli::{Backward, Forward, Train}; use ndarray::{Array, Array3}; use num_traits::Zero; use std::ops::Add; #[derive(Clone, Debug)] pub struct
<G>(pub G); impl<G> Forward for Map3One<G> where G: Forward, { type Input = Array3<G::Input>; type Internal = Array3<G::Internal>; type Output = Array3<G::Output>; fn forward(&self, input: &Self::Input) -> (Self::Internal, Self::Output) { let both = input.iter().map(|input| self.0.forward(...
Map3One
identifier_name
map3one.rs
use itertools::izip; use mli::{Backward, Forward, Train}; use ndarray::{Array, Array3}; use num_traits::Zero; use std::ops::Add; #[derive(Clone, Debug)] pub struct Map3One<G>(pub G); impl<G> Forward for Map3One<G> where G: Forward, { type Input = Array3<G::Input>; type Internal = Array3<G::Internal>; ...
}
{ self.0.train(train_delta); }
identifier_body
useMountedEffect.ts
import { useEffect, useLayoutEffect, useRef, EffectCallback, DependencyList, } from 'react' /* Behaves like `useEffect`, but won't fire after the initial render of a component. */ export const useMountedEffect = ( effect: EffectCallback, inputs?: DependencyList ) => { const isFirstRender = useRef(t...
if (isFirstRender.current) { isFirstRender.current = false return } return effect() }, inputs) // eslint-disable-line react-hooks/exhaustive-deps } export const useMountedLayoutEffect = ( effect: EffectCallback, inputs?: DependencyList ) => { const isFirstRender = useRef(true) useL...
random_line_split
useMountedEffect.ts
import { useEffect, useLayoutEffect, useRef, EffectCallback, DependencyList, } from 'react' /* Behaves like `useEffect`, but won't fire after the initial render of a component. */ export const useMountedEffect = ( effect: EffectCallback, inputs?: DependencyList ) => { const isFirstRender = useRef(t...
return effect() }, inputs) // eslint-disable-line react-hooks/exhaustive-deps } export const useMountedLayoutEffect = ( effect: EffectCallback, inputs?: DependencyList ) => { const isFirstRender = useRef(true) useLayoutEffect(() => { if (isFirstRender.current) { isFirstRender.current = false...
{ isFirstRender.current = false return }
conditional_block
interpolate.py
import numpy as np import matplotlib.pyplot as plt from astropy.io import fits from scipy.interpolate import interp1d,splev,splrep def extractSpectrum(filename): """ NAME: extractSpectrum PURPOSE: To open an input fits file from SDSS and extract the relevant components, ...
INPUTS: points Set of new points to get interpolated values for. lam The wavelengths of the data points flux The fluxes of the data points method The method of interpolation to use. Valide values include 'interp1d:linear', 'interp1d:quadr...
methods. Defined for convienience.
random_line_split
interpolate.py
import numpy as np import matplotlib.pyplot as plt from astropy.io import fits from scipy.interpolate import interp1d,splev,splrep def extractSpectrum(filename): """ NAME: extractSpectrum PURPOSE: To open an input fits file from SDSS and extract the relevant components, ...
""" if method == 'interp1d:linear': f = interp1d(lam, flux, assume_sorted = True) return f(points) if method == 'interp1d:quadratic': f = interp1d(lam, flux, kind = 'quadratic', assume_sorted = True) return f(points) if method == 'splrep': return splev(poi...
""" NAME: interpolate PURPOSE: General purpose function that can call and use various scipy.interpolate methods. Defined for convienience. INPUTS: points Set of new points to get interpolated values for. lam The wavelengths of the data points ...
identifier_body
interpolate.py
import numpy as np import matplotlib.pyplot as plt from astropy.io import fits from scipy.interpolate import interp1d,splev,splrep def extractSpectrum(filename): """ NAME: extractSpectrum PURPOSE: To open an input fits file from SDSS and extract the relevant components, ...
if method == 'splrep': return splev(points, splrep(lam, flux)) raise Exception("You didn't choose a proper interpolating method") #First extract the flux and corresponding wavelength fileName = 'spec-4053-55591-0938.fits' lam, flux = extractSpectrum(fileName) #Now let's plot it, without any ...
f = interp1d(lam, flux, kind = 'quadratic', assume_sorted = True) return f(points)
conditional_block
interpolate.py
import numpy as np import matplotlib.pyplot as plt from astropy.io import fits from scipy.interpolate import interp1d,splev,splrep def
(filename): """ NAME: extractSpectrum PURPOSE: To open an input fits file from SDSS and extract the relevant components, namely the flux and corresponding wavelength. INPUTS: filename The path and filename (including the extension) to the ...
extractSpectrum
identifier_name
templateService.js
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v12.0.2 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c ...
// returns the template if it is loaded, or null if it is not loaded // but will call the callback when it is loaded TemplateService.prototype.getTemplate = function (url, callback) { var templateFromCache = this.templateCache[url]; if (templateFromCache) { return templateFromCa...
{ this.templateCache = {}; this.waitingCallbacks = {}; }
identifier_body
templateService.js
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v12.0.2 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c ...
return null; }; TemplateService.prototype.handleHttpResult = function (httpResult, url) { if (httpResult.status !== 200 || httpResult.response === null) { console.warn('Unable to get template error ' + httpResult.status + ' - ' + url); return; } // respons...
} // caller needs to wait for template to load, so return null
random_line_split
templateService.js
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v12.0.2 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c ...
() { this.templateCache = {}; this.waitingCallbacks = {}; } // returns the template if it is loaded, or null if it is not loaded // but will call the callback when it is loaded TemplateService.prototype.getTemplate = function (url, callback) { var templateFromCache = this.templat...
TemplateService
identifier_name
package.py
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Dust(Package): """du + rust = dust. Like du but more intuitive.""" homepage = "https:...
depends_on("rust") sanity_check_is_file = [join_path("bin", "dust")] def install(self, spec, prefix): cargo = which("cargo") cargo("install", "--root", prefix, "--path", ".") @run_after("install") def check_install(self): print("Attempt to call 'dust' with '--version'") ...
random_line_split
package.py
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Dust(Package): """du + rust = dust. Like du but more intuitive.""" homepage = "https:...
(self, spec, prefix): cargo = which("cargo") cargo("install", "--root", prefix, "--path", ".") @run_after("install") def check_install(self): print("Attempt to call 'dust' with '--version'") dust = Executable(join_path(self.spec["dust"].prefix.bin, "dust")) output = dust...
install
identifier_name
package.py
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Dust(Package):
@run_after("install") def check_install(self): print("Attempt to call 'dust' with '--version'") dust = Executable(join_path(self.spec["dust"].prefix.bin, "dust")) output = dust( "--version", output=str.split, ) print("stdout received fromm dust is ...
"""du + rust = dust. Like du but more intuitive.""" homepage = "https://github.com/bootandy/dust" url = "https://github.com/bootandy/dust/archive/v0.7.5.tar.gz" maintainers = ["fangohr"] version( "0.7.5", sha256="f892aaf7a0a7852e12d01b2ced6c2484fb6dc5fe7562abdf0c44a2d08aa52618", )...
identifier_body
thread.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/. //! Multi-threading //! //! = Examples //! //! ---- //! let mut array = [1u8; 1024]; //! { //! let res = scoped(|...
//! for i in 0..SIZE { //! assert!(array[i] == 2); //! } //! ---- pub use lrs_thread::{ Builder, spawn, scoped, JoinGuard, cpu_count, CpuMask, cpus, set_cpus, unshare, current_cpu, join_namespace, thread_id, exit, deschedule, enter_strict_mode, at_exit, }; pub use lrs_thread::ids::{ UserIds, GroupI...
random_line_split
borrowck-uniq-via-lend.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 ...
{ }
identifier_body
borrowck-uniq-via-lend.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 ...
{ g: H } struct H { h: Box<int> } let mut v = F {f: G {g: H {h: box 3}}}; borrow(&*v.f.g.h); } fn aliased_imm() { let mut v = box 3i; let _w = &v; borrow(&*v); } fn aliased_mut() { let mut v = box 3i; let _w = &mut v; borrow(&*v); //~ ERROR cannot borrow `*v` } fn aliased_other()...
G
identifier_name
borrowck-uniq-via-lend.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 ...
struct G { g: H } struct H { h: Box<int> } let mut v = F {f: G {g: H {h: box 3}}}; borrow(&*v.f.g.h); } fn aliased_imm() { let mut v = box 3i; let _w = &v; borrow(&*v); } fn aliased_mut() { let mut v = box 3i; let _w = &mut v; borrow(&*v); //~ ERROR cannot borrow `*v` } fn ali...
borrow(&*v.f); } fn local_recs() { struct F { f: G }
random_line_split
distinct.rs
use std::collections::{HashMap, HashSet}; use std::collections::hash_state::DefaultState; use std::hash::{hash, Hash, SipHasher}; use std::default::Default; use communication::Data; use communication::pact::Exchange; use construction::{Stream, GraphBuilder}; use construction::operators::unary::UnaryNotifyExt; use se...
(&self) -> Stream<G, D> { let mut elements: HashMap<_, HashSet<_, DefaultState<SipHasher>>> = HashMap::new(); let exch = Exchange::new(|x| hash::<_,SipHasher>(&x)); self.unary_notify(exch, "Distinct", vec![], move |input, output, notificator| { while let Some((time, data)) = input.pu...
distinct
identifier_name
distinct.rs
use std::collections::{HashMap, HashSet}; use std::collections::hash_state::DefaultState; use std::hash::{hash, Hash, SipHasher}; use std::default::Default; use communication::Data; use communication::pact::Exchange; use construction::{Stream, GraphBuilder}; use construction::operators::unary::UnaryNotifyExt; use se...
} notificator.notify_at(&time); } while let Some((time, _count)) = notificator.next() { elements.remove(&time); } }) } fn distinct_batch(&self) -> Stream<G, D> { let mut elements: HashMap<_, HashSet<_, Defaul...
{ session.give(datum); }
conditional_block
distinct.rs
use std::collections::{HashMap, HashSet}; use std::collections::hash_state::DefaultState;
use communication::pact::Exchange; use construction::{Stream, GraphBuilder}; use construction::operators::unary::UnaryNotifyExt; use serialization::Serializable; pub trait DistinctExtensionTrait { fn distinct(&self) -> Self; fn distinct_batch(&self) -> Self; } impl<G: GraphBuilder, D: Data+Hash+Eq+Serializa...
use std::hash::{hash, Hash, SipHasher}; use std::default::Default; use communication::Data;
random_line_split
distinct.rs
use std::collections::{HashMap, HashSet}; use std::collections::hash_state::DefaultState; use std::hash::{hash, Hash, SipHasher}; use std::default::Default; use communication::Data; use communication::pact::Exchange; use construction::{Stream, GraphBuilder}; use construction::operators::unary::UnaryNotifyExt; use se...
} fn distinct_batch(&self) -> Stream<G, D> { let mut elements: HashMap<_, HashSet<_, DefaultState<SipHasher>>> = HashMap::new(); let exch = Exchange::new(|x| hash::<_,SipHasher>(&x)); self.unary_notify(exch, "DistinctBlock", vec![], move |input, output, notificator| { while...
{ let mut elements: HashMap<_, HashSet<_, DefaultState<SipHasher>>> = HashMap::new(); let exch = Exchange::new(|x| hash::<_,SipHasher>(&x)); self.unary_notify(exch, "Distinct", vec![], move |input, output, notificator| { while let Some((time, data)) = input.pull() { l...
identifier_body
hdrs.py
"""HTTP Headers constants.""" from .multidict import upstr METH_ANY = upstr('*') METH_CONNECT = upstr('CONNECT') METH_HEAD = upstr('HEAD') METH_GET = upstr('GET') METH_DELETE = upstr('DELETE') METH_OPTIONS = upstr('OPTIONS') METH_PATCH = upstr('PATCH') METH_POST = upstr('POST') METH_PUT = upstr('PUT') METH_TRACE = ups...
COOKIE = upstr('COOKIE') DATE = upstr('DATE') DESTINATION = upstr('DESTINATION') DIGEST = upstr('DIGEST') ETAG = upstr('ETAG') EXPECT = upstr('EXPECT') EXPIRES = upstr('EXPIRES') FROM = upstr('FROM') HOST = upstr('HOST') IF_MATCH = upstr('IF-MATCH') IF_MODIFIED_SINCE = upstr('IF-MODIFIED-SINCE') IF_NONE_MATCH = upstr('...
random_line_split
NotificationCenter.ts
/********************************************************************* * Copyright (c) 2019 Red Hat, Inc. * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifi...
(timeout: number = TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM) { Logger.debug('NotificationCenter.clickIconOnStatusBar'); const statusBarNotificationsLocator: By = By.xpath('(//div[@id=\'theia-statusBar\']//div[@class=\'area right\']//div[@title=\'Toggle Bottom Panel\']/preceding-si...
clickIconOnStatusBar
identifier_name
NotificationCenter.ts
/********************************************************************* * Copyright (c) 2019 Red Hat, Inc. * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifi...
async waitClosing(timeout: number = TimeoutConstants.TS_NOTIFICATION_CENTER_TIMEOUT) { Logger.debug(`NotificationCenter.waitClosing`); const notificationCenterClosedLocator: By = By.css('.theia-notification-center.closed'); await this.driverHelper.waitPresence(notificationCenterClosedLoc...
{ Logger.debug(`NotificationCenter.clickCloseAllNotificationsButton`); const closeAllButtonLocator: By = By.css('.theia-notification-center-header-actions .clear-all'); await this.driverHelper.waitAndClick(closeAllButtonLocator, timeout); }
identifier_body
NotificationCenter.ts
/********************************************************************* * Copyright (c) 2019 Red Hat, Inc. * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifi...
@injectable() export class NotificationCenter { constructor(@inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper) { } async waitOpening(timeout: number = TimeoutConstants.TS_NOTIFICATION_CENTER_TIMEOUT) { Logger.debug('NotificationCenter.waitOpening'); await this.driverHel...
random_line_split
sdk.py
# -*- coding: UTF-8 -*- import hashlib import base64 import datetime import urllib2 import json class TemplateSMS: account_sid = '' account_token = '' app_id = '' server_ip = '' server_port = '' soft_version = '' timestamp = '' def set_account(self, account_sid, token): self.a...
(self, app_id): self.app_id = app_id def send_template_sms(self, to, random, valid_min, temp_id): now_date = datetime.datetime.now() self.timestamp = now_date.strftime("%Y%m%d%H%M%S") signature = self.account_sid + self.account_token + self.timestamp sig = hashlib.md5() ...
set_app_id
identifier_name
sdk.py
# -*- coding: UTF-8 -*- import hashlib import base64 import datetime import urllib2 import json class TemplateSMS:
def send_template_sms(self, to, random, valid_min, temp_id): now_date = datetime.datetime.now() self.timestamp = now_date.strftime("%Y%m%d%H%M%S") signature = self.account_sid + self.account_token + self.timestamp sig = hashlib.md5() sig.update(signature) sig = sig.he...
account_sid = '' account_token = '' app_id = '' server_ip = '' server_port = '' soft_version = '' timestamp = '' def set_account(self, account_sid, token): self.account_sid = account_sid self.account_token = token def __init__(self, ip, port, version): self.serv...
identifier_body
sdk.py
# -*- coding: UTF-8 -*- import hashlib import base64 import datetime import urllib2 import json class TemplateSMS: account_sid = '' account_token = '' app_id = '' server_ip = '' server_port = '' soft_version = '' timestamp = ''
def set_account(self, account_sid, token): self.account_sid = account_sid self.account_token = token def __init__(self, ip, port, version): self.server_ip = ip self.server_port = port self.soft_version = version def set_app_id(self, app_id): self.app_id = ap...
random_line_split
file.js
/* * @package jsDAV * @subpackage DAV * @copyright Copyright(c) 2011 Ajax.org B.V. <info AT ajax DOT org> * @author Mike de Boer <info AT mikedeboer DOT nl> * @license http://github.com/mikedeboer/jsDAV/blob/master/LICENSE MIT License */ "use strict"; var jsDAV_Ftp_Node = require("./node").jsDAV_Ftp_Node; var j...
(path, ftp) { this.path = path || ""; this.ftp = ftp; } exports.jsDAV_Ftp_File = jsDAV_Ftp_File; (function() { this.implement(jsDAV_iFile); /** * Creates or updates the data of this node * * @param {mixed} data * @return void */ this.put = function(data, type, cbftpput) {...
jsDAV_Ftp_File
identifier_name
file.js
/* * @package jsDAV * @subpackage DAV * @copyright Copyright(c) 2011 Ajax.org B.V. <info AT ajax DOT org> * @author Mike de Boer <info AT mikedeboer DOT nl> * @license http://github.com/mikedeboer/jsDAV/blob/master/LICENSE MIT License */ "use strict"; var jsDAV_Ftp_Node = require("./node").jsDAV_Ftp_Node; var j...
*/ this.getContentType = function(cbftpmime) { return cbftpmime(null, Util.mime.type(this.path)); }; }).call(jsDAV_Ftp_File.prototype = new jsDAV_Ftp_Node());
* If null is returned, we'll assume application/octet-stream * * @return mixed
random_line_split
file.js
/* * @package jsDAV * @subpackage DAV * @copyright Copyright(c) 2011 Ajax.org B.V. <info AT ajax DOT org> * @author Mike de Boer <info AT mikedeboer DOT nl> * @license http://github.com/mikedeboer/jsDAV/blob/master/LICENSE MIT License */ "use strict"; var jsDAV_Ftp_Node = require("./node").jsDAV_Ftp_Node; var j...
exports.jsDAV_Ftp_File = jsDAV_Ftp_File; (function() { this.implement(jsDAV_iFile); /** * Creates or updates the data of this node * * @param {mixed} data * @return void */ this.put = function(data, type, cbftpput) { var path = this.path; var ftp = this.ftp; ...
{ this.path = path || ""; this.ftp = ftp; }
identifier_body
test_gpio.js
/* Copyright 2015 Samsung Electronics Co., Ltd. * * 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 *
* * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the Licens...
* http://www.apache.org/licenses/LICENSE-2.0
random_line_split
class.rs
Clone, Debug, PartialEq, PartialOrd, Eq, Ord)] pub enum ClassMember<T: Atom> { /// A single atom Atom(T), /// A range of atoms Range(T, T) } impl<T: Atom> ClassMember<T> { /// Map the class-member's atoms to a different type pub fn map_atoms<U, F>(self, f: F) -> ClassMember<U> where F...
} /// Create a new Class instance from an iterator of ClassMember instances. pub fn from_members<I>(m: I) -> Self where I: IntoIterator<Item=ClassMember<T>> { Class{members: m.into_iter().collect()} } /// Map the atoms in the class to a different atom type. pub fn map_atoms...
/// Create a new Class instance with members taken from the given iterator. pub fn new<I,U>(items: I) -> Self where I: IntoIterator<Item=U>, ClassMember<T>: From<U> { Class{members: Vec::from_iter(items.into_iter().map(|x| x.into()))}
random_line_split
class.rs
, Debug, PartialEq, PartialOrd, Eq, Ord)] pub enum ClassMember<T: Atom> { /// A single atom Atom(T), /// A range of atoms Range(T, T) } impl<T: Atom> ClassMember<T> { /// Map the class-member's atoms to a different type pub fn map_atoms<U, F>(self, f: F) -> ClassMember<U> where F: Fn(T...
/// Fetch an iterator over the atoms specified in the class. pub fn iter<'a>(&'a self) -> impl Iterator<Item=T> + 'a where T: Step { self.members.iter().flat_map(|m| m.iter()) } } impl<T: Atom> Debug for Class<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "[{}...
{ self.members.iter() }
identifier_body
class.rs
, Debug, PartialEq, PartialOrd, Eq, Ord)] pub enum ClassMember<T: Atom> { /// A single atom Atom(T), /// A range of atoms Range(T, T) } impl<T: Atom> ClassMember<T> { /// Map the class-member's atoms to a different type pub fn map_atoms<U, F>(self, f: F) -> ClassMember<U> where F: Fn(T...
(&self, cm: &'a ClassMember<T>) -> bool { self.iter_members().any(|m| cm == m) } } impl<T: Atom> set::Contains<T> for Class<T> { /// Check if any member of the class matches the given atom. fn contains(&self, x: T) -> bool { self.matches(x) } } impl<T: Atom + Step> set::IsSubsetOf<T> fo...
contains
identifier_name
Locator.ts
// The MIT License (MIT) // // Copyright (c) 2016 Simon Mika // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy...
toString(): string { let result = "" if (this.scheme.length > 0) result += this.scheme.join("+") + ":" if (!this.authority.isEmpty) result += "//" + this.authority.toString() else if (this.scheme.length > 0) result += "//" if (this.path) { let path = this.path.join("/") if (path[0] != "." || ...
{ return new Locator(this.scheme, this.authority, path instanceof Array ? [...this.path, ...path] : [...this.path, path], this.query, this.fragment) }
identifier_body
Locator.ts
// The MIT License (MIT) // // Copyright (c) 2016 Simon Mika // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy...
if (Object.keys(this.query).length > 0) result += "?" + this.query.toString() if (this.fragment) result += "#" + this.fragment return result } static readonly empty = new Locator(undefined, undefined, undefined, undefined, undefined) static parse(data?: string): Locator | undefined { let result: Locat...
{ let path = this.path.join("/") if (path[0] != "." || result.length > 0) path = "/" + path result += path }
conditional_block
Locator.ts
// The MIT License (MIT) // // Copyright (c) 2016 Simon Mika // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy...
const result: T[] = [] while (count-- > 0) result.push(value) return result } normalize(): Locator { let skip = 0 const path = this.path.reverse().filter((item, index) => { let r = false if ((item == "" || item == ".") && index < this.path.length - 1) r = false // do nothing else if ...
} private createArray<T>(value: T, count: number): T[] {
random_line_split
Locator.ts
// The MIT License (MIT) // // Copyright (c) 2016 Simon Mika // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy...
<T>(value: T, count: number): T[] { const result: T[] = [] while (count-- > 0) result.push(value) return result } normalize(): Locator { let skip = 0 const path = this.path.reverse().filter((item, index) => { let r = false if ((item == "" || item == ".") && index < this.path.length - 1) r...
createArray
identifier_name
test_solvers.py
def test_swap_back(): # A solution comes back from solve even though it shouldn't be: f(x) is # in the solution's Integral as the upper limit. When solve is fixed this # test should be removed. For now, since there are ode's that come back # with these sorts of solutions, the swap_back feature is perf...
return sstr(sympify(e).evalf(n, **options), full_prec=True)
identifier_body
test_solvers.py
) + 1, x ) == GS_TRANSCENDENTAL assert guess_solve_strategy( 2*cos(x)-y, x ) == GS_TRANSCENDENTAL assert guess_solve_strategy( exp(x) + exp(-x) - y, x ) == GS_TRANSCENDENTAL assert guess_solve_strategy(3**x-10, x) == GS_TRANSCENDENTAL assert guess_solve_strategy(-3**x+10, x) == GS_TRANSCENDENTAL as...
(): """ Test for solving on equations that can be converted to a polynomial equation multiplying both sides of the equation by x**m """ x = Symbol('x') assert solve(x + 1/x - 1, x) in \ [[ Rational(1,2) + I*sqrt(3)/2, Rational(1,2) - I*sqrt(3)/2], [ Rational(1,2) - I*sqrt(3)/2,...
test_solve_polynomial_cv_2
identifier_name
test_solvers.py
(1,4),x) assert set([NS(w, n=2) for w in ans]) == \ set(['0.010', '-9.5 + 2.8*I', '0', '-9.5 - 2.8*I']) def test_solve_polynomial_cv_1b(): x, a = symbols('x a') assert set(solve(4*x*(1 - a*x**(S(1)/2)), x)) == set([S(0), 1/a**2]) assert set(solve(x * (x**(S(1)/3) - 3), x)) == set([S(0), S(27)])...
y = Function('y')(t) a11,a12,a21,a22,b1,b2 = symbols('a11,a12,a21,a22,b1,b2')
random_line_split
subnet-cal.py
#!/usr/bin/python
my_subnet = "255.255.255.0" ip = my_ip.split(".") print ip # Check the validity of the ip address while True: #my_ip = input("Enter a ip address:") if int(ip[0]) <= 223 and (int(ip[1]) != 169 or int(ip[2]) != 254) and (int(ip[1]) <= 254 and int(ip[2]) <= 254 and int(ip[3]) <= 254): print "You entered a valid ip"...
#my_subnet = input("Enter Subnet address:") my_ip = "192.168.1.100"
random_line_split
subnet-cal.py
#!/usr/bin/python #my_subnet = input("Enter Subnet address:") my_ip = "192.168.1.100" my_subnet = "255.255.255.0" ip = my_ip.split(".") print ip # Check the validity of the ip address while True: #my_ip = input("Enter a ip address:") if int(ip[0]) <= 223 and (int(ip[1]) != 169 or int(ip[2]) != 254) and (int(ip[...
print bin_ip print type(bin_ip)
print bin(int(a)).split("b")[1].zfill(8) bin_ip += bin(int(a)).split("b")[1].zfill(8)
conditional_block
Constructor.tsx
import * as React from "react" import { Router, Route, Redirect, IndexRoute } from "react-router" import { ajaxGet, ajaxPost } from './Services'; import { openModal } from './Modals'; import { Dic } from './Globals'; import { Lite, Entity, ModifiableEntity, EmbeddedEntity, SelectorMessage, EntityPack, MixinEntity...
>(valueOrPromise: T | Promise<T>) { if (valueOrPromise && (valueOrPromise as Promise<T>).then) return valueOrPromise as Promise<T>; return Promise.resolve(valueOrPromise as T); } function assertCorrect(m: ModifiableEntity) { if (m && !m.isNew && !(m as Entity).id) throw new Error(...
Promise<T
identifier_name
Constructor.tsx
import * as React from "react" import { Router, Route, Redirect, IndexRoute } from "react-router" import { ajaxGet, ajaxPost } from './Services'; import { openModal } from './Modals'; import { Dic } from './Globals'; import { Lite, Entity, ModifiableEntity, EmbeddedEntity, SelectorMessage, EntityPack, MixinEntity...
export function registerConstructor<T extends ModifiableEntity>(type: Type<T>, constructor: (typeName: string) => T | Promise<T | undefined>) { customConstructors[type.typeName] = constructor; }
if (m && !m.isNew && !(m as Entity).id) throw new Error("Member 'isNew' expected after constructor"); if (m.modified == undefined) throw new Error("Member 'modified' expected after constructor"); }
identifier_body
Constructor.tsx
import * as React from "react" import { Router, Route, Redirect, IndexRoute } from "react-router" import { ajaxGet, ajaxPost } from './Services'; import { openModal } from './Modals'; import { Dic } from './Globals'; import { Lite, Entity, ModifiableEntity, EmbeddedEntity, SelectorMessage, EntityPack, MixinEntity...
return asPromise(c(typeName)).then<EntityPack<ModifiableEntity> | undefined>(e => { if (e == undefined) return undefined; assertCorrect(e); return Navigator.toEntityPack(e); }); const ti = getTypeInfo(typeName); if (ti) { ...
const typeName = (type as Type<any>).typeName || type as string; const c = customConstructors[typeName]; if (c)
random_line_split
seed.ts
import { tryGet } from '@seagull/libraries' import { FixtureStorage as FxSt } from '@seagull/seed' import { Http } from '@seagull/services-http' import * as fs from 'fs' import { injectable } from 'inversify' import 'reflect-metadata' import { SoapError, SoapFaultError } from '../error' import { ClientOptions, Cred...
throw new Error() } } catch { const wsdlString = await this.getWsdl(opts) seed.set(wsdlString) } return seed } private async getSeedResponse( seed: FxSt<ISoapResponse>, fnc: ClientFunction, args: any ) { try { const response = seed.get() handleSee...
random_line_split
seed.ts
import { tryGet } from '@seagull/libraries' import { FixtureStorage as FxSt } from '@seagull/seed' import { Http } from '@seagull/services-http' import * as fs from 'fs' import { injectable } from 'inversify' import 'reflect-metadata' import { SoapError, SoapFaultError } from '../error' import { ClientOptions, Cred...
(fault: NodeSoapFault11 | NodeSoapFault12): IXmlFault { return 'Reason' in fault ? { code: unpack(fault.Code.Value), description: unpack(fault.Reason.Text), statusCode: unpack(fault.statusCode), subcode: unpack(fault.Code.Subcode && fault.Code.Subcode.Value), } ...
convertFault
identifier_name
seed.ts
import { tryGet } from '@seagull/libraries' import { FixtureStorage as FxSt } from '@seagull/seed' import { Http } from '@seagull/services-http' import * as fs from 'fs' import { injectable } from 'inversify' import 'reflect-metadata' import { SoapError, SoapFaultError } from '../error' import { ClientOptions, Cred...
throw new SoapError('Unknown error', error) } private convertFault(fault: NodeSoapFault11 | NodeSoapFault12): IXmlFault { return 'Reason' in fault ? { code: unpack(fault.Code.Value), description: unpack(fault.Reason.Text), statusCode: unpack(fault.statusCode), ...
{ const xmlFault: IXmlFault = this.convertFault(fault) const xmlResponse = (error as NodeSoapFaultError).body seed.set({ xmlFault, xmlResponse }) throw new SoapFaultError( `Fault ${xmlFault.code}: ${xmlFault.description}`, xmlFault ) }
conditional_block
seed.ts
import { tryGet } from '@seagull/libraries' import { FixtureStorage as FxSt } from '@seagull/seed' import { Http } from '@seagull/services-http' import * as fs from 'fs' import { injectable } from 'inversify' import 'reflect-metadata' import { SoapError, SoapFaultError } from '../error' import { ClientOptions, Cred...
private getAuthHeader(credentials: Credentials): { Authorization: string } { const { username, password } = credentials const base64Creds = new Buffer(username + ':' + password).toString('base64') const Authorization = `Basic ${base64Creds}` return { Authorization } } private handleResponseErro...
{ const creds = opts.credentials const headers = creds ? this.getAuthHeader(creds) : {} const credentials = creds ? 'include' : undefined const init = { credentials, headers, method: 'GET', mode: 'cors' } const wsdlString = await (await new Http().get(opts.wsdlPath, init)).text() return wsdlStri...
identifier_body
ntp-sync.py
import math import numpy import pyaudio import time import ntplib def sine(frequency, length, rate): length = int(length * rate) factor = float(frequency) * (math.pi * 2) / rate return numpy.sin(numpy.arange(length) * factor) chunks = [] chunks.append(sine(440, 1, 44100)) chunk = numpy.concatenate(chun...
p = pyaudio.PyAudio() stream = p.open(format=pyaudio.paFloat32, channels=1, rate=44100, output=1) last = 0 print("[ntp-sync] getting clock") c = ntplib.NTPClient() response = c.request('pool.ntp.org', version=3) print("[ntp-sync] clock offset %s" % response.offset) while True: curtime = int(math.floor(time.time()...
random_line_split
ntp-sync.py
import math import numpy import pyaudio import time import ntplib def sine(frequency, length, rate):
chunks = [] chunks.append(sine(440, 1, 44100)) chunk = numpy.concatenate(chunks) * 0.25 p = pyaudio.PyAudio() stream = p.open(format=pyaudio.paFloat32, channels=1, rate=44100, output=1) last = 0 print("[ntp-sync] getting clock") c = ntplib.NTPClient() response = c.request('pool.ntp.org', version=3) print("[ntp-sy...
length = int(length * rate) factor = float(frequency) * (math.pi * 2) / rate return numpy.sin(numpy.arange(length) * factor)
identifier_body
ntp-sync.py
import math import numpy import pyaudio import time import ntplib def sine(frequency, length, rate): length = int(length * rate) factor = float(frequency) * (math.pi * 2) / rate return numpy.sin(numpy.arange(length) * factor) chunks = [] chunks.append(sine(440, 1, 44100)) chunk = numpy.concatenate(chun...
stream.close() p.terminate()
curtime = int(math.floor(time.time() + response.offset)) if (curtime % 5) == 0 and curtime > last: print curtime print("beep") last = curtime stream.write(chunk.astype(numpy.float32).tostring())
conditional_block
ntp-sync.py
import math import numpy import pyaudio import time import ntplib def
(frequency, length, rate): length = int(length * rate) factor = float(frequency) * (math.pi * 2) / rate return numpy.sin(numpy.arange(length) * factor) chunks = [] chunks.append(sine(440, 1, 44100)) chunk = numpy.concatenate(chunks) * 0.25 p = pyaudio.PyAudio() stream = p.open(format=pyaudio.paFloat32, ...
sine
identifier_name
xrspace.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::reflect_dom_object; use cra...
} else { unreachable!() } } pub fn session(&self) -> &XRSession { &self.session } }
{ frame.target_ray_origin.map(cast_transform) }
conditional_block
xrspace.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::reflect_dom_object; use cra...
(session: &XRSession) -> XRSpace { XRSpace { eventtarget: EventTarget::new_inherited(), session: Dom::from_ref(session), input_source: Default::default(), is_grip_space: false, } } fn new_inputspace_inner( session: &XRSession, inpu...
new_inherited
identifier_name
xrspace.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::reflect_dom_object; use cra...
BaseSpace::TargetRay(source.id()) }; Space { base, offset: RigidTransform3D::identity(), } } else { panic!("invalid space found") } } } impl XRSpace { /// Gets pose represented by this space /// ...
} else if let Some(source) = self.input_source.get() { let base = if self.is_grip_space { BaseSpace::Grip(source.id()) } else {
random_line_split
xrspace.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::reflect_dom_object; use cra...
} impl XRSpace { /// Gets pose represented by this space /// /// The reference origin used is common between all /// get_pose calls for spaces from the same device, so this can be used to compare /// with other spaces pub fn get_pose(&self, base_pose: &Frame) -> Option<ApiPose> { if le...
{ if let Some(rs) = self.downcast::<XRReferenceSpace>() { rs.space() } else if let Some(j) = self.downcast::<XRJointSpace>() { j.space() } else if let Some(source) = self.input_source.get() { let base = if self.is_grip_space { BaseSpace::Grip(s...
identifier_body
roman-numerals-macro.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. //
// except according to those terms. // aux-build:roman_numerals.rs // ignore-stage1 #![feature(phase)] #[phase(plugin)] extern crate roman_numerals; pub fn main() { assert_eq!(rn!(MMXV), 2015); assert_eq!(rn!(MCMXCIX), 1999); assert_eq!(rn!(XXV), 25); assert_eq!(rn!(MDCLXVI), 1666); assert_eq!(r...
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed
random_line_split
roman-numerals-macro.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 ...
() { assert_eq!(rn!(MMXV), 2015); assert_eq!(rn!(MCMXCIX), 1999); assert_eq!(rn!(XXV), 25); assert_eq!(rn!(MDCLXVI), 1666); assert_eq!(rn!(MMMDCCCLXXXVIII), 3888); assert_eq!(rn!(MMXIV), 2014); }
main
identifier_name
roman-numerals-macro.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 ...
{ assert_eq!(rn!(MMXV), 2015); assert_eq!(rn!(MCMXCIX), 1999); assert_eq!(rn!(XXV), 25); assert_eq!(rn!(MDCLXVI), 1666); assert_eq!(rn!(MMMDCCCLXXXVIII), 3888); assert_eq!(rn!(MMXIV), 2014); }
identifier_body
client.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity 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....
} impl HashFetch for Client { fn fetch(&self, hash: H256, on_done: Box<Fn(Result<PathBuf, Error>) + Send>) -> Result<(), Error> { debug!(target: "dapps", "Fetching: {:?}", hash); let url = try!( self.contract.resolve(hash.to_vec()).map(|content| match content { URLHintResult::Dapp(dapp) => { dapp.ur...
{ Client { contract: URLHintContract::new(contract), fetch: Mutex::new(FetchClient::default()), } }
identifier_body
client.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity 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....
else { Ok(path) } } debug!(target: "dapps", "Content fetched, validating hash ({:?})", hash); on_done(validate_hash(hash, result)) })).map_err(Into::into) } }
{ Err(Error::HashMismatch{ got: content_hash, expected: hash }) }
conditional_block
client.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity 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....
); debug!(target: "dapps", "Resolved {:?} to {:?}. Fetching...", hash, url); self.fetch.lock().request_async(&url, Default::default(), Box::new(move |result| { fn validate_hash(hash: H256, result: Result<PathBuf, FetchError>) -> Result<PathBuf, Error> { let path = try!(result); let mut file_reader = ...
}, URLHintResult::Content(content) => { content.url }, }).ok_or_else(|| Error::NoResolution)
random_line_split
client.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity 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....
(error: FetchError) -> Self { Error::Fetch(error) } } impl From<io::Error> for Error { fn from(error: io::Error) -> Self { Error::IO(error) } } /// Default Hash-fetching client using on-chain contract to resolve hashes to URLs. pub struct Client { contract: URLHintContract, fetch: Mutex<FetchClient>, } impl...
from
identifier_name
TextAvatar.tsx
import * as React from 'react'; import { IRootStyleProps, IOnClickProps } from '../'; import * as styles from './text-avatar.css'; const classNames = require('classnames'); export interface ITextAvatarProps extends IOnClickProps, IRootStyleProps { text: string; shape?: 'circle' | 'square' | 'squareRound' | 'round'...
(): JSX.Element { const { shape, text, className, style, onClick } = this.props; let shapeClassName = ''; if (['circle', 'square', 'squareRound', 'round'].indexOf(shape!) >= 0 ) { shapeClassName = styles[shape!]; } else { shapeClassName = styles.circle; } return ( <div ...
render
identifier_name
TextAvatar.tsx
import * as React from 'react'; import { IRootStyleProps, IOnClickProps } from '../'; import * as styles from './text-avatar.css'; const classNames = require('classnames'); export interface ITextAvatarProps extends IOnClickProps, IRootStyleProps { text: string; shape?: 'circle' | 'square' | 'squareRound' | 'round'...
}; render(): JSX.Element { const { shape, text, className, style, onClick } = this.props; let shapeClassName = ''; if (['circle', 'square', 'squareRound', 'round'].indexOf(shape!) >= 0 ) { shapeClassName = styles[shape!]; } else { shapeClassName = styles.circle; } return ( ...
public static defaultProps: Partial<ITextAvatarProps> = { shape: 'circle', className: '', style: {}, onClick: () => {},
random_line_split
TextAvatar.tsx
import * as React from 'react'; import { IRootStyleProps, IOnClickProps } from '../'; import * as styles from './text-avatar.css'; const classNames = require('classnames'); export interface ITextAvatarProps extends IOnClickProps, IRootStyleProps { text: string; shape?: 'circle' | 'square' | 'squareRound' | 'round'...
else { shapeClassName = styles.circle; } return ( <div className={classNames(styles.root, shapeClassName, className)} style={style} onClick={onClick} > <div className={styles.element}>{text}</div> </div> ); } }
{ shapeClassName = styles[shape!]; }
conditional_block
ui.js
(ui.msg["l_page_abbr"], ui.state.doc, ui.state.view) document.title = view_title + " / " + ui.library; } function render_view_selector (ui) { var d = ui.state.doc; var current = ui.state.view; var count = d.views.length; var div = J.dom ("div", {id : ui.vie...
i, ev) { Debug.log ("Show record %o !", ev); } function show_preview (ui, ev){ Debug.log ("Show preview %o !", ev); } function show_divisions (ui, ev){ Debug.log ("Show division %o !", ev); } function button (ui, id, onclick) { var b = J.$(id); var label = document.createTextNode (ui.msg[id]); ...
w_record (u
identifier_name
ui.js
(ui.msg["l_page_abbr"], ui.state.doc, ui.state.view) document.title = view_title + " / " + ui.library; } function render_view_selector (ui) { var d = ui.state.doc; var current = ui.state.view; var count = d.views.length; var div = J.dom ("div", {id : ui.vie...
} ui.image.onload = function () { finish (); } ui.image.onerror = function () { Debug.log ("Image could not be loaded"); } ui.image.src = Doc.view_image_uri (ui.state.doc, ui.state.view);; } function render (ui) { render_view_img (ui); render_view_selector (ui); render_webpage_titl...
render_canvas (ui); J.classify (ui.canvas, "la_enter_right", false); J.classify (ui.canvas_last, "la_enter_right", true); }
conditional_block
ui.js
(ui.msg["l_page_abbr"], ui.state.doc, ui.state.view) document.title = view_title + " / " + ui.library; } function render_view_selector (ui) {
J.ev (a, "click", J.app (ev_set_view, ui, v)); } else { a = J.dom ("a", { "class" : "l_highlight" }); } if (view.label) a.appendChild (J.txt (view.label)); else { a.appendChild (J.txt ("v")); a.appendChild (J.dom ("sub", {}, v.toString ())) ...
var d = ui.state.doc; var current = ui.state.view; var count = d.views.length; var div = J.dom ("div", {id : ui.view_sel.id }); if (count < 10) { var page_abbr = null; for (var v = 0; v < count; v++) { var view = d.views[v]; if (view.label && !page_abbr) ...
identifier_body
ui.js
_txt (ui.msg["l_page_abbr"], ui.state.doc, ui.state.view) document.title = view_title + " / " + ui.library; } function render_view_selector (ui) { var d = ui.state.doc; var current = ui.state.view; var count = d.views.length; var div = J.dom ("div", {id : ui...
{ record : button (ui, "l_record", show_record), divisions : button (ui, "l_divs", show
ui.nav =
random_line_split
variable.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
def set_val(self, value): if value: fernet = get_fernet() self._val = fernet.encrypt(bytes(value, 'utf-8')).decode() self.is_encrypted = fernet.is_encrypted @declared_attr def val(cls): return synonym('_val', descriptor=property(c...
if self._val and self.is_encrypted: try: fernet = get_fernet() return fernet.decrypt(bytes(self._val, 'utf-8')).decode() except InvalidFernetToken: self.log.error("Can't decrypt _val for key=%s, invalid token or value", self.key) re...
identifier_body
variable.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
Variable.delete(key, session=session) session.add(Variable(key=key, val=stored_value)) # type: ignore session.flush() @classmethod @provide_session def delete(cls, key, session=None): session.query(cls).filter(cls.key == key).delete() def rotate_fernet_key(self): ...
stored_value = str(value)
conditional_block
variable.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
( cls, key: str, default_var: Any = __NO_DEFAULT_SENTINEL, deserialize_json: bool = False, session=None ): obj = session.query(cls).filter(cls.key == key).first() if obj is None: if default_var is not cls.__NO_DEFAULT_SENTINEL: retu...
get
identifier_name
variable.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import json from typing import Any from cryptography.fernet import InvalidToken as InvalidFernetToken from sqlalchemy impo...
# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an
random_line_split
set_mat_col.rs
//! Given: //! //! `y <- alpha * A * x` //! //! Test that //! //! `y[i] = alpha * A[i, :] * x` //! //! for any valid `i` #![feature(custom_attribute)] #![feature(plugin)] #![plugin(quickcheck_macros)] extern crate approx; extern crate complex; extern crate linalg; extern crate quickcheck; extern crate rand; #[macro_...
use complex::{c64, c128}; use linalg::prelude::*; use quickcheck::TestResult; macro_rules! tests { ($($t:ident),+) => { $( #[quickcheck] fn $t((srow, scol): (u32, u32), (nrows, ncols): (u32, u32), i: u32) -> TestResult { enforce! {...
use linalg::prelude::*; use quickcheck::TestResult; mod transposed {
random_line_split
books-add.componetn.ts
import { Component, OnInit, OnDestroy } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms'; import { BooksService } from '../../services/books.service'; import { AuthorsService } from '../../services/authors.service'; import { BookFormService } from '../../forms/book-fotm.service'; @Compone...
constructor( private booksService: BooksService, private authorsService: AuthorsService, private bookFormService: BookFormService) {} ngOnInit() { /* Create form */ this.addBookForm = this.bookFormService.createBookForm(); this.authorsService.getAuthors() .then(res => { console.log(res); ...
addBookForm: FormGroup; bookAuthors: Array<any>; subBookForm: any;
random_line_split
books-add.componetn.ts
import { Component, OnInit, OnDestroy } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms'; import { BooksService } from '../../services/books.service'; import { AuthorsService } from '../../services/authors.service'; import { BookFormService } from '../../forms/book-fotm.service'; @Compone...
() { this.addBookForm.reset(); } }
onCancelEdit
identifier_name
books-add.componetn.ts
import { Component, OnInit, OnDestroy } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms'; import { BooksService } from '../../services/books.service'; import { AuthorsService } from '../../services/authors.service'; import { BookFormService } from '../../forms/book-fotm.service'; @Compone...
else { this.booksService.addBook(book); } this.addBookForm.reset(); } onCancelEdit() { this.addBookForm.reset(); } }
{ this.booksService.editBook(book); }
conditional_block
books-add.componetn.ts
import { Component, OnInit, OnDestroy } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms'; import { BooksService } from '../../services/books.service'; import { AuthorsService } from '../../services/authors.service'; import { BookFormService } from '../../forms/book-fotm.service'; @Compone...
onCancelEdit() { this.addBookForm.reset(); } }
{ if(book.id) { this.booksService.editBook(book); } else { this.booksService.addBook(book); } this.addBookForm.reset(); }
identifier_body
item-attributes.rs
// Copyright 2012-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-MI...
mod test_stmt_multi_attr_outer { pub fn f() { #[attr1 = "val"] #[attr2 = "val"] static x: int = 10; #[attr1 = "val"] #[attr2 = "val"] fn f() { } #[attr1 = "val"] #[attr2 = "val"] mod mod1 { } mod rustrt { #[attr1...
random_line_split
item-attributes.rs
// Copyright 2012-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-MI...
#[attr = "val"] mod mod1 { } mod rustrt { #[attr = "val"] extern { } } } } mod test_stmt_multi_attr_outer { pub fn f() { #[attr1 = "val"] #[attr2 = "val"] static x: int = 10; #[attr1 = "val"] ...
{ }
identifier_body
item-attributes.rs
// Copyright 2012-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-MI...
() { } #[attr = "val"] mod mod1 { } mod rustrt { #[attr = "val"] extern { } } } } mod test_stmt_multi_attr_outer { pub fn f() { #[attr1 = "val"] #[attr2 = "val"] static x: int = 10; #[attr1 = "val"] ...
f
identifier_name
main.rs
extern crate rustbox; use std::env; use std::io::Result; use std::path::Path; mod filedata; use filedata::FileData; mod display; use display::Display; fn main() { let fd = match init_data() { Ok(v) => v, Err(e) => { println!("could not open specified file: {}", e); return; } }; let display = Displ...
}
{ let mut args = env::args().skip(1); if args.len() > 0 { let path_str = args.next().unwrap_or(String::new()); let path_str_copy = path_str.clone(); let path = Path::new(&path_str_copy); if path.exists() == false { Ok(FileData::new_with_name(path_str)) } else { FileData::from(path_str) ...
identifier_body
main.rs
extern crate rustbox; use std::env; use std::io::Result; use std::path::Path; mod filedata; use filedata::FileData; mod display; use display::Display; fn main() { let fd = match init_data() { Ok(v) => v, Err(e) =>
}; let display = Display::new(fd); display.run(); } //create a new data object from cmd args fn init_data() -> Result<FileData> { let mut args = env::args().skip(1); if args.len() > 0 { let path_str = args.next().unwrap_or(String::new()); let path_str_copy = path_str.clone(); let path = Path::new(&path_s...
{ println!("could not open specified file: {}", e); return; }
conditional_block
main.rs
extern crate rustbox; use std::env; use std::io::Result; use std::path::Path; mod filedata; use filedata::FileData;
mod display; use display::Display; fn main() { let fd = match init_data() { Ok(v) => v, Err(e) => { println!("could not open specified file: {}", e); return; } }; let display = Display::new(fd); display.run(); } //create a new data object from cmd args fn init_data() -> Result<FileData> { let mut...
random_line_split