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
hdtorrents.py
# Author: Idan Gutman # Modified by jkaberg, https://github.com/jkaberg for SceneAccess # URL: https://sickrage.ca # # This file is part of SickRage. # # SickRage 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...
return True login_params = {'uid': self.username, 'pwd': self.password, 'submit': 'Confirm'} try: response = self.session.post(self.urls['login'], data=login_params, timeout=30).text except Exception: sickrage....
if any(dict_from_cookiejar(self.session.cookies).values()):
random_line_split
hdtorrents.py
# Author: Idan Gutman # Modified by jkaberg, https://github.com/jkaberg for SceneAccess # URL: https://sickrage.ca # # This file is part of SickRage. # # SickRage 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...
seeders = try_int(cells[labels.index('S')].get_text(strip=True)) leechers = try_int(cells[labels.index('L')].get_text(strip=True)) torrent_size = cells[labels.index('Size')].get_text() size = convert_size(torrent_size, -1, ['B', 'KIB', 'M...
continue
conditional_block
app.py
#!/usr/bin/env python #-*- coding: utf-8 -*- from __future__ import unicode_literals import sqlite3 from flask import Flask, render_template, g, current_app, request from flask.ext.paginate import Pagination app = Flask(__name__) app.config.from_pyfile('app.cfg') @app.before_request def before_request(): g.conn...
def get_css_framework(): return current_app.config.get('CSS_FRAMEWORK', 'bootstrap3') def get_link_size(): return current_app.config.get('LINK_SIZE', 'sm') def show_single_page_or_not(): return current_app.config.get('SHOW_SINGLE_PAGE', False) def get_page_items(): page = int(request.args.get('p...
random_line_split
app.py
#!/usr/bin/env python #-*- coding: utf-8 -*- from __future__ import unicode_literals import sqlite3 from flask import Flask, render_template, g, current_app, request from flask.ext.paginate import Pagination app = Flask(__name__) app.config.from_pyfile('app.cfg') @app.before_request def before_request(): g.conn...
else: per_page = int(per_page) offset = (page - 1) * per_page return page, per_page, offset def get_pagination(**kwargs): kwargs.setdefault('record_name', 'records') return Pagination(css_framework=get_css_framework(), link_size=get_link_size(), ...
per_page = current_app.config.get('PER_PAGE', 10)
conditional_block
app.py
#!/usr/bin/env python #-*- coding: utf-8 -*- from __future__ import unicode_literals import sqlite3 from flask import Flask, render_template, g, current_app, request from flask.ext.paginate import Pagination app = Flask(__name__) app.config.from_pyfile('app.cfg') @app.before_request def before_request(): g.conn...
if __name__ == '__main__': app.run(debug=True)
kwargs.setdefault('record_name', 'records') return Pagination(css_framework=get_css_framework(), link_size=get_link_size(), show_single_page=show_single_page_or_not(), **kwargs )
identifier_body
app.py
#!/usr/bin/env python #-*- coding: utf-8 -*- from __future__ import unicode_literals import sqlite3 from flask import Flask, render_template, g, current_app, request from flask.ext.paginate import Pagination app = Flask(__name__) app.config.from_pyfile('app.cfg') @app.before_request def before_request(): g.conn...
(**kwargs): kwargs.setdefault('record_name', 'records') return Pagination(css_framework=get_css_framework(), link_size=get_link_size(), show_single_page=show_single_page_or_not(), **kwargs ) if __name__ == '__main__': a...
get_pagination
identifier_name
list.py
# Copyright 2012 Rackspace # # 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...
def take_action(self, parsed_args): client = get_client(parsed_args) marker = parsed_args.marker if parsed_args.marker else None limit = parsed_args.limit if parsed_args.limit else None kwargs = {'marker': marker, 'limit': limit} if parsed_args.namespace: kwa...
parser = super(ListCommand, self).get_parser(prog_name=prog_name) parser.add_argument('--namespace', dest='namespace') return parser
identifier_body
list.py
# Copyright 2012 Rackspace # # 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...
(BaseListCommand, Lister): """ Return a list of the configuration values. """ log = logging.getLogger(__name__) def get_parser(self, prog_name): parser = super(ListCommand, self).get_parser(prog_name=prog_name) parser.add_argument('--namespace', dest='namespace') return pars...
ListCommand
identifier_name
list.py
# Copyright 2012 Rackspace # # 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...
return (('ID', 'Value'), result)
for value in values]
random_line_split
list.py
# Copyright 2012 Rackspace # # 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...
else: result = client.configuration.list(**kwargs) values = result['values'] metadata = result['metadata'] parsed_args.returned_metadata = metadata result = [(value['id'], value['value']) for value in values] return (('ID', 'Value'), resu...
kwargs['namespace'] = parsed_args.namespace result = client.configuration.list_for_namespace(**kwargs)
conditional_block
20.rs
/* Problem 20: Factorial digit sum * * n! means n × (n − 1) × ... × 3 × 2 × 1 * * For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, * and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. * * Find the sum of the digits in the number 100! */ use num::bigint::{BigUint, ToBigUint}; us...
-> u32 { chr.to_digit(10).unwrap() }
ar)
identifier_name
20.rs
/* Problem 20: Factorial digit sum * * n! means n × (n − 1) × ... × 3 × 2 × 1 * * For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, * and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. * * Find the sum of the digits in the number 100! */ use num::bigint::{BigUint, ToBigUint}; us...
remaining -= 1; } result } fn to_i(chr: char) -> u32 { chr.to_digit(10).unwrap() }
let mut result: BigUint = One::one(); let mut remaining: u32 = n; while remaining > 0 { result = result * remaining.to_biguint().unwrap();
random_line_split
20.rs
/* Problem 20: Factorial digit sum * * n! means n × (n − 1) × ... × 3 × 2 × 1 * * For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, * and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. * * Find the sum of the digits in the number 100! */ use num::bigint::{BigUint, ToBigUint}; us...
al(n: u32) -> BigUint { let mut result: BigUint = One::one(); let mut remaining: u32 = n; while remaining > 0 { result = result * remaining.to_biguint().unwrap(); remaining -= 1; } result } fn to_i(chr: char) -> u32 { chr.to_digit(10).unwrap() }
rnum = factorial(100).to_string(); let result = strnum.chars().fold(0, |digit, sum| digit + to_i(sum)); println!("{}", result); } fn factori
identifier_body
issue-32995.rs
// Copyright 2017 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 ...
fn foo<X:Default>() { let d : X() = Default::default(); //~^ ERROR parenthesized parameters may only be used with a trait //~| WARN previously accepted }
}
random_line_split
issue-32995.rs
// Copyright 2017 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 o : Box<Send + ::std::marker()::Sync> = Box::new(1); //~^ ERROR parenthesized parameters may only be used with a trait //~| WARN previously accepted } fn foo<X:Default>() { let d : X() = Default::default(); //~^ ERROR parenthesized parameters may only be used with a trait //~| WARN previo...
{ let x: usize() = 1; //~^ ERROR parenthesized parameters may only be used with a trait //~| WARN previously accepted let b: ::std::boxed()::Box<_> = Box::new(1); //~^ ERROR parenthesized parameters may only be used with a trait //~| WARN previously accepted let p = ::std::str::()::from_ut...
identifier_body
issue-32995.rs
// Copyright 2017 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 x: usize() = 1; //~^ ERROR parenthesized parameters may only be used with a trait //~| WARN previously accepted let b: ::std::boxed()::Box<_> = Box::new(1); //~^ ERROR parenthesized parameters may only be used with a trait //~| WARN previously accepted let p = ::std::str::()::from...
main
identifier_name
lib.rs
//! Compile-time generated maps and sets. //! //! The `phf::Map` and `phf::Set` types have roughly comparable performance to //! a standard hash table, but can be generated as compile-time static values. //! //! # Usage //! //! If the `macros` Cargo feature is enabled, the `phf_map`, `phf_set`, //! `phf_ordered_map`, a...
#[doc(inline)] pub use self::map::Map; #[doc(inline)] pub use self::set::Set; #[doc(inline)] pub use self::ordered_map::OrderedMap; #[doc(inline)] pub use self::ordered_set::OrderedSet; pub mod map; pub mod set; pub mod ordered_map; pub mod ordered_set; // WARNING: this is not considered part of phf's public API and ...
pub use phf_shared::PhfHash;
random_line_split
lib.rs
//! Compile-time generated maps and sets. //! //! The `phf::Map` and `phf::Set` types have roughly comparable performance to //! a standard hash table, but can be generated as compile-time static values. //! //! # Usage //! //! If the `macros` Cargo feature is enabled, the `phf_map`, `phf_set`, //! `phf_ordered_map`, a...
(&self) -> &[T] { match *self { Slice::Static(t) => t, #[cfg(feature = "std")] Slice::Dynamic(ref t) => t, } } }
deref
identifier_name
mod.rs
pub use self::{ bit_board::BitBoard, board::Board, player::{AiPlayer, PlayerKind}, }; mod bit_board; mod board; mod multi_direction; mod player; #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub struct Point(pub u32, pub u32); impl Point { fn from_offset(off: u32, size: Size) -> Point { Point(...
Side::White => Side::Black, } } }
random_line_split
mod.rs
pub use self::{ bit_board::BitBoard, board::Board, player::{AiPlayer, PlayerKind}, }; mod bit_board; mod board; mod multi_direction; mod player; #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub struct Point(pub u32, pub u32); impl Point { fn from_offset(off: u32, size: Size) -> Point { Point(...
{ Black, White, } impl Side { pub fn flip(self) -> Side { match self { Side::Black => Side::White, Side::White => Side::Black, } } }
Side
identifier_name
S15.10.4.1_A3_T2.js
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: let P be the empty string if pattern is undefined es5id: 15.10.4.1_A3_T2 description: RegExp is new RegExp(void 0) ---*/ var __re = new RegExp(void 0); //CHECK#2 if (__re.mu...
//CHECK#4 if (__re.ignoreCase !== false) { $ERROR('#4: __re = new RegExp(void 0); __re.ignoreCase === false. Actual: ' + (__re.ignoreCase)); }
{ $ERROR('#3: __re = new RegExp(void 0); __re.global === false. Actual: ' + (__re.global)); }
conditional_block
S15.10.4.1_A3_T2.js
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: let P be the empty string if pattern is undefined es5id: 15.10.4.1_A3_T2 description: RegExp is new RegExp(void 0) ---*/ var __re = new RegExp(void 0); //CHECK#2 if (__re.mu...
$ERROR('#3: __re = new RegExp(void 0); __re.global === false. Actual: ' + (__re.global)); } //CHECK#4 if (__re.ignoreCase !== false) { $ERROR('#4: __re = new RegExp(void 0); __re.ignoreCase === false. Actual: ' + (__re.ignoreCase)); }
//CHECK#3 if (__re.global !== false) {
random_line_split
v28_to_v29.py
#!/usr/bin/env python # -*- coding: utf-8 import sys import argparse import anvio.db as db import anvio.utils as utils import anvio.terminal as terminal from anvio.errors import ConfigError run = terminal.Run() progress = terminal.Progress()
current_version, next_version = [x[1:] for x in __name__.split('_to_')] def migrate(db_path): if db_path is None: raise ConfigError("No database path is given.") # make sure someone is not being funny utils.is_profile_db(db_path) # make sure the version is accurate profile_db = db.DB(db_p...
random_line_split
v28_to_v29.py
#!/usr/bin/env python # -*- coding: utf-8 import sys import argparse import anvio.db as db import anvio.utils as utils import anvio.terminal as terminal from anvio.errors import ConfigError run = terminal.Run() progress = terminal.Progress() current_version, next_version = [x[1:] for x in __name__.split('_to_')] ...
progress.end() run.info_single('Your profile db is now %s, and you know this deserves a celebration.' % next_version, nl_after=1, nl_before=1, mc='green') if __name__ == '__main__': parser = argparse.ArgumentParser(description='A simple script to upgrade profile database from version %s to version %s' %...
if db_path is None: raise ConfigError("No database path is given.") # make sure someone is not being funny utils.is_profile_db(db_path) # make sure the version is accurate profile_db = db.DB(db_path, None, ignore_version = True) if str(profile_db.get_version()) != current_version: ...
identifier_body
v28_to_v29.py
#!/usr/bin/env python # -*- coding: utf-8 import sys import argparse import anvio.db as db import anvio.utils as utils import anvio.terminal as terminal from anvio.errors import ConfigError run = terminal.Run() progress = terminal.Progress() current_version, next_version = [x[1:] for x in __name__.split('_to_')] ...
# make sure someone is not being funny utils.is_profile_db(db_path) # make sure the version is accurate profile_db = db.DB(db_path, None, ignore_version = True) if str(profile_db.get_version()) != current_version: raise ConfigError("Version of this profile database is not %s (hence, this ...
raise ConfigError("No database path is given.")
conditional_block
v28_to_v29.py
#!/usr/bin/env python # -*- coding: utf-8 import sys import argparse import anvio.db as db import anvio.utils as utils import anvio.terminal as terminal from anvio.errors import ConfigError run = terminal.Run() progress = terminal.Progress() current_version, next_version = [x[1:] for x in __name__.split('_to_')] ...
(db_path): if db_path is None: raise ConfigError("No database path is given.") # make sure someone is not being funny utils.is_profile_db(db_path) # make sure the version is accurate profile_db = db.DB(db_path, None, ignore_version = True) if str(profile_db.get_version()) != current_ve...
migrate
identifier_name
types.rs
//! Holmes Language Types //! //! The types defined in this module are used to define the parts of the Holmes //! language itself, and are used for writing rules, facts, etc. use pg::dyn::{Type, Value}; /// A `Predicate` is a name combined with a list of typed slots, e.g. /// /// ```c /// foo(uint64, string) /// ``` /...
(&self, other: &MatchExpr) -> bool { use self::MatchExpr::*; match (self, other) { (&Unbound, &Unbound) => true, (&Var(x), &Var(y)) => x == y, (&Const(ref v), &Const(ref vv)) => v == vv, _ => false, } } } /// A `BindExpr` is what appears on th...
eq
identifier_name
types.rs
//! Holmes Language Types //! //! The types defined in this module are used to define the parts of the Holmes //! language itself, and are used for writing rules, facts, etc. use pg::dyn::{Type, Value}; /// A `Predicate` is a name combined with a list of typed slots, e.g. /// /// ```c /// foo(uint64, string) /// ``` /...
/// use std::sync::Arc; /// Predicate { /// name: "foo".to_string(), /// description: None, /// fields: vec![Field { /// name: None, /// description: None, /// type_: Arc::new(types::UInt64) /// }, Field { /// name: None, /// description: None, /// type_: ...
/// ``` /// use holmes::pg::dyn::types; /// use holmes::engine::types::{Predicate, Field};
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 PyPyyaml(PythonPackage): """PyYAML is a YAML parser and emitter for Python.""" homepa...
version('5.1', sha256='436bc774ecf7c103814098159fbb84c2715d25980175292c648f2da143909f95') version('3.13', sha256='3ef3092145e9b70e3ddd2c7ad59bdd0252a94dfe3949721633e41344de00a6bf') version('3.12', sha256='592766c6303207a20efc445587778322d7f73b161bd994f227adaa341ba212ab') version('3.11', sha256='c36...
version('5.2', sha256='c0ee8eca2c582d29c3c2ec6e2c4f703d1b7f1fb10bc72317355a746057e7346c') version('5.1.2', sha256='01adf0b6c6f61bd11af6e10ca52b7d4057dd0be0343eb9283c878cf3af56aee4')
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 PyPyyaml(PythonPackage): """PyYAML is a YAML parser and emitter for Python.""" homepa...
else: args.insert(0, '--without-libyaml') super(PyPyyaml, self).setup_py(*args, **kwargs) def build_ext_args(self, spec, prefix): args = [] if spec.satisfies('@:5 +libyaml'): args.extend([ spec['libyaml'].libs.search_flags, ...
args.insert(0, '--with-libyaml')
conditional_block
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 PyPyyaml(PythonPackage): """PyYAML is a YAML parser and emitter for Python.""" homepa...
(self, spec, prefix): args = [] if spec.satisfies('@:5 +libyaml'): args.extend([ spec['libyaml'].libs.search_flags, spec['libyaml'].headers.include_flags, ]) return args # Tests need to be re-added since `phases` was overridden r...
build_ext_args
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 PyPyyaml(PythonPackage):
depends_on('python@3.6:', type=('build', 'run'), when='@6.0:') depends_on('libyaml', when='+libyaml') depends_on('py-setuptools', when='@6.0:') depends_on('py-cython', when='@6.0: +libyaml') phases = ['build_ext', 'install'] @property def import_modules(self): modules = ['yaml'] ...
"""PyYAML is a YAML parser and emitter for Python.""" homepage = "https://pyyaml.org/wiki/PyYAML" pypi = "PyYAML/PyYAML-5.3.1.tar.gz" git = "https://github.com/yaml/pyyaml.git" maintainers = ['adamjstewart'] version('6.0', sha256='68fb519c14306fec9720a2a5b45bc9f0c8d1b9c72adf45c37baedfcd949...
identifier_body
tool_base.py
# The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Data. # THE DATA IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND ...
(self, model_config): """ Creates a new instance of a modelica simulation. dictionary : model_config Mandatory Keys : 'model_name' (str), 'model_file_name' (str) Optional Keys : 'MSL_version' (str), 'variable_filter' ([str]), ...
_initialize
identifier_name
tool_base.py
Projects # Agency (DARPA) and delivered to the U.S. Government with Unlimited Rights # as defined in DFARS 252.227-7013. # Permission is hereby granted, free of charge, to any person obtaining a # copy of this data, including any software or models in source or binary # form, as well as any drawings, specificat...
try: import _winreg as wr key = wr.OpenKey(wr.HKEY_LOCAL_MACHINE, r'software\meta', 0, wr.KEY_READ) try: self.max_simulation_time = wr.QueryValueEx(key, 'MAX_SIMULATION_TIME')[0] print 'Found MAX_SIMULATION_TIME in registry, va...
conditional_block
tool_base.py
The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Data. # THE DATA IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND N...
self.lib_package_names.append(lib_name) if os.name == 'nt': try: import _win
if 'lib_package_names' in model_config: for lib_name in self.model_config['lib_package_names']: if lib_name:
random_line_split
tool_base.py
# The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Data. # THE DATA IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND ...
# always use highest level of debugging log.setLevel(logging.DEBUG) log.debug(" --- ==== ******************************* ==== ---") log.info(" --- ==== ******* New Run Started ******* ==== ---") self.date_time = '{0}'.format(datetime.datetime.today()) log.debug(" -...
""" Creates a new instance of a modelica simulation. dictionary : model_config Mandatory Keys : 'model_name' (str), 'model_file_name' (str) Optional Keys : 'MSL_version' (str), 'variable_filter' ([str]), 'result_file' (str), 'experiment' ({s...
identifier_body
yaku.py
import warnings class Yaku: yaku_id = None tenhou_id = None name = None han_open = None han_closed = None is_yakuman = None def __init__(self, yaku_id=None):
def __str__(self): return self.name def __repr__(self): # for calls in array return self.__str__() def is_condition_met(self, hand, *args): """ Is this yaku exists in the hand? :param: hand :param: args: some yaku requires additional attributes ...
self.tenhou_id = None self.yaku_id = yaku_id self.set_attributes()
identifier_body
yaku.py
import warnings class Yaku: yaku_id = None tenhou_id = None name = None han_open = None han_closed = None is_yakuman = None
self.yaku_id = yaku_id self.set_attributes() def __str__(self): return self.name def __repr__(self): # for calls in array return self.__str__() def is_condition_met(self, hand, *args): """ Is this yaku exists in the hand? :param: hand ...
def __init__(self, yaku_id=None): self.tenhou_id = None
random_line_split
yaku.py
import warnings class Yaku: yaku_id = None tenhou_id = None name = None han_open = None han_closed = None is_yakuman = None def __init__(self, yaku_id=None): self.tenhou_id = None self.yaku_id = yaku_id self.set_attributes() def __str__(self): return ...
(self): warnings.warn("Use .name attribute instead of .english attribute", DeprecationWarning) return self.name @property def japanese(self): warnings.warn("Use .name attribute instead of .japanese attribute", DeprecationWarning) return self.name
english
identifier_name
lib.rs
#[macro_use] extern crate log; use special_fun::FloatSpecial; use std::collections::VecDeque; use std::f64; #[derive(Clone, Debug)] pub struct PhiFailureDetector { min_stddev: f64, history_size: usize, buf: VecDeque<u64>, prev_heartbeat: Option<u64>, } impl PhiFailureDetector { pub fn new() -> Ph...
/// Returns the time t (within epsilon) at which phi will be >= val . pub fn next_crossing_at(&self, now: u64, threshold: f64) -> u64 { let phappened = 1.0 - (10.0f64).powf(-threshold); let x = phappened.norm_inv(); let mean = stats::mean(self.buf.iter().cloned()); let stddev = ...
None => 0.0, } }
random_line_split
lib.rs
#[macro_use] extern crate log; use special_fun::FloatSpecial; use std::collections::VecDeque; use std::f64; #[derive(Clone, Debug)] pub struct PhiFailureDetector { min_stddev: f64, history_size: usize, buf: VecDeque<u64>, prev_heartbeat: Option<u64>, } impl PhiFailureDetector { pub fn
() -> PhiFailureDetector { Self::default() } pub fn min_stddev(self, min_stddev: f64) -> PhiFailureDetector { assert!(min_stddev > 0.0, "min_stddev must be > 0.0"); PhiFailureDetector { min_stddev, ..self } } pub fn history_size(self, count: usize) -> PhiFailureDetector { ...
new
identifier_name
lib.rs
#[macro_use] extern crate log; use special_fun::FloatSpecial; use std::collections::VecDeque; use std::f64; #[derive(Clone, Debug)] pub struct PhiFailureDetector { min_stddev: f64, history_size: usize, buf: VecDeque<u64>, prev_heartbeat: Option<u64>, } impl PhiFailureDetector { pub fn new() -> Ph...
} } /// def ϕ(Tnow ) = − log10(Plater (Tnow − Tlast)) pub fn phi(&self, now: u64) -> f64 { match &self.prev_heartbeat { Some(prev_time) if now > *prev_time => { trace!( "now:{} - prev_heartbeat:{} = {:?}", now, ...
{ if t < *prev { return; }; let delta = t - *prev; self.buf.push_back(delta); *prev = t; if self.buf.len() > self.history_size { let _ = self.buf.pop_front(); } ...
conditional_block
lib.rs
#[macro_use] extern crate log; use special_fun::FloatSpecial; use std::collections::VecDeque; use std::f64; #[derive(Clone, Debug)] pub struct PhiFailureDetector { min_stddev: f64, history_size: usize, buf: VecDeque<u64>, prev_heartbeat: Option<u64>, } impl PhiFailureDetector { pub fn new() -> Ph...
} #[test] fn should_recover() { env_logger::try_init().unwrap_or_default(); let mut detector = PhiFailureDetector::new().history_size(3); for t in 0..10 { detector.heartbeat(t); let phi = detector.phi(t); trace!("at:{:?}, phi:{:?}; det: {:?}", t,...
env_logger::try_init().unwrap_or_default(); let mut detector = PhiFailureDetector::new(); for t in 0..100 { detector.heartbeat(t); let phi = detector.phi(t); trace!("at:{:?}, phi:{:?}; det: {:?}", t, phi, detector); if t > 10 { assert...
identifier_body
test_redirects.py
from django.test import TestCase from builds.models import Version from projects.models import Project class RedirectTests(TestCase): fixtures = ["eric", "test_data"] def setUp(self): self.client.login(username='eric', password='test') r = self.client.post( '/dashboard/import/', ...
# Keep this around for now, until we come up with a nicer interface """ def test_inproper_subdomain(self): r = self.client.get('/en/', HTTP_HOST = 'pip.readthedocs.org') self.assertEqual(r.status_code, 404) """ def test_proper_subdomain_and_url(self): r = self.client.get(...
r = self.client.get('/', HTTP_HOST = 'pip.readthedocs.org') self.assertEqual(r.status_code, 302) self.assertEqual(r._headers['location'], ('Location', 'http://pip.readthedocs.org/en/latest/'))
identifier_body
test_redirects.py
from django.test import TestCase from builds.models import Version from projects.models import Project class RedirectTests(TestCase): fixtures = ["eric", "test_data"] def setUp(self): self.client.login(username='eric', password='test') r = self.client.post( '/dashboard/import/', ...
(self): r = self.client.get('/docs/pip/page/test.html') self.assertEqual(r.status_code, 302) self.assertEqual(r._headers['location'], ('Location', 'http://testserver/docs/pip/en/latest/test.html'))
test_proper_page_on_main_site
identifier_name
test_redirects.py
from django.test import TestCase
from projects.models import Project class RedirectTests(TestCase): fixtures = ["eric", "test_data"] def setUp(self): self.client.login(username='eric', password='test') r = self.client.post( '/dashboard/import/', {'repo_type': 'git', 'name': 'Pip', 'tags': ...
from builds.models import Version
random_line_split
volumemetadata.py
Floor, Boston, MA 02110-1301 USA # # Refer to the README and COPYING files for full details of the license # from __future__ import absolute_import import logging import time import six from vdsm.storage import constants as sc from vdsm.storage import exception # SIZE property was deprecated in metadata v5, but ...
@description.setter def description(self, desc): self._description = self.validate_description(desc) @property def capacity(self): return self._capacity @capacity.setter def capacity(self, value): self._capacity = self._validate_integer("capacity", value) @proper...
return self._description
identifier_body
volumemetadata.py
Floor, Boston, MA 02110-1301 USA # # Refer to the README and COPYING files for full details of the license # from __future__ import absolute_import import logging import time import six from vdsm.storage import constants as sc from vdsm.storage import exception # SIZE property was deprecated in metadata v5, but ...
for key, (name, validate) in ATTRIBUTES.items(): try: # FIXME: remove pylint skip when bug fixed: # https://github.com/PyCQA/pylint/issues/5113 metadata[name] = validate(md[key]) # pylint: disable=not-callable except KeyError: errors.append("Require...
md[sc.SEQUENCE] = sc.DEFAULT_SEQUENCE
conditional_block
volumemetadata.py
Floor, Boston, MA 02110-1301 USA # # Refer to the README and COPYING files for full details of the license # from __future__ import absolute_import import logging import time import six from vdsm.storage import constants as sc from vdsm.storage import exception # SIZE property was deprecated in metadata v5, but ...
(self, desc): self._description = self.validate_description(desc) @property def capacity(self): return self._capacity @capacity.setter def capacity(self, value): self._capacity = self._validate_integer("capacity", value) @property def ctime(self): return self._...
description
identifier_name
volumemetadata.py
TYPE: ("voltype", str), sc.DISKTYPE: ("disktype", str), sc.DESCRIPTION: ("description", str), sc.LEGALITY: ("legality", str), sc.CTIME: ("ctime", int), sc.GENERATION: ("generation", int), sc.SEQUENCE: ("sequence", int), } def _lines_to_dict(lines): md = {} errors = [] for line in ...
random_line_split
latex.rs
use std::io::IoResult; use collections::HashMap; use backend::Backend; use colors; pub struct LatexBackend { contexts: Vec<~str>, } impl LatexBackend { pub fn new() -> LatexBackend { LatexBackend { contexts: Vec::new(), } } } static HEADER: &'static str = "\ \\usepackage{xco...
fn start(&mut self, w: &mut Writer, ty: &str) -> IoResult<()> { if ty != "comment" { if colors::get_types().contains(&ty.to_owned()) { try!(write!(w, "\\\\textcolor\\{{}\\}\\{", ty)); } if ty == "attribute" { try!(w.write_str("#")); ...
{ try!(w.write_line("\\end{Highlighting}")); try!(w.write_line("\\end{Shaded}")); Ok(()) }
identifier_body
latex.rs
use std::io::IoResult; use collections::HashMap; use backend::Backend; use colors; pub struct LatexBackend { contexts: Vec<~str>, } impl LatexBackend { pub fn new() -> LatexBackend { LatexBackend { contexts: Vec::new(), } } } static HEADER: &'static str = "\ \\usepackage{xco...
(&mut self, w: &mut Writer, ty: &str) -> IoResult<()> { if ty != "comment" { if colors::get_types().contains(&ty.to_owned()) { try!(write!(w, "\\\\textcolor\\{{}\\}\\{", ty)); } if ty == "attribute" { try!(w.write_str("#")); } ...
start
identifier_name
latex.rs
use std::io::IoResult; use collections::HashMap; use backend::Backend; use colors; pub struct LatexBackend { contexts: Vec<~str>, } impl LatexBackend { pub fn new() -> LatexBackend { LatexBackend { contexts: Vec::new(), } } } static HEADER: &'static str = "\ \\usepackage{xco...
} first = false; } let old_len = text.len(); let text = text.trim_right_chars('\n').to_owned(); let new_len = text.len(); range(0, old_len - new_len).advance(|_| { result.push_char('\n'); true...
result.push_str("}");
random_line_split
latex.rs
use std::io::IoResult; use collections::HashMap; use backend::Backend; use colors; pub struct LatexBackend { contexts: Vec<~str>, } impl LatexBackend { pub fn new() -> LatexBackend { LatexBackend { contexts: Vec::new(), } } } static HEADER: &'static str = "\ \\usepackage{xco...
self.contexts.pop(); Ok(()) } fn text(&mut self, w: &mut Writer, text: &str) -> IoResult<()> { fn escape_latex(text: &str) -> ~str { let mut result = StrBuf::new(); let mut escape = false; for c in text.chars() { if escape { ...
{ if ty == "attribute" { try!(w.write_str("]")); } if colors::get_types().contains(&ty.to_owned()) { try!(w.write_str("}")); } }
conditional_block
websiteServing.js
/** * findRoutingRule - find applicable routing rule from bucket metadata * @param {RoutingRule []} routingRules - array of routingRule objects * @param {string} key - object key * @param {number} [errCode] - error code to match if applicable * @return {object | undefined} redirectInfo -- comprised of all of the ...
// redirect to another object in bucket redirectInfo.replaceKeyWith = location.slice(1); // when redirect info is set by x-amz-website-redirect-location header // to another key in the same bucket // AWS only returns the path in the location response header redirectInfo.j...
*/ export function extractRedirectInfo(location) { const redirectInfo = { redirectLocationHeader: true }; if (location.startsWith('/')) {
random_line_split
websiteServing.js
/** * findRoutingRule - find applicable routing rule from bucket metadata * @param {RoutingRule []} routingRules - array of routingRule objects * @param {string} key - object key * @param {number} [errCode] - error code to match if applicable * @return {object | undefined} redirectInfo -- comprised of all of the ...
{ const redirectInfo = { redirectLocationHeader: true }; if (location.startsWith('/')) { // redirect to another object in bucket redirectInfo.replaceKeyWith = location.slice(1); // when redirect info is set by x-amz-website-redirect-location header // to another key in the same b...
identifier_body
websiteServing.js
/** * findRoutingRule - find applicable routing rule from bucket metadata * @param {RoutingRule []} routingRules - array of routingRule objects * @param {string} key - object key * @param {number} [errCode] - error code to match if applicable * @return {object | undefined} redirectInfo -- comprised of all of the ...
(routingRules, key, errCode) { if (!routingRules || routingRules.length === 0) { return undefined; } // For AWS compat: // 1) use first routing rules whose conditions are satisfied // 2) for matching prefix no need to check closest match. first // match wins // 3) there can be a mat...
findRoutingRule
identifier_name
websiteServing.js
/** * findRoutingRule - find applicable routing rule from bucket metadata * @param {RoutingRule []} routingRules - array of routingRule objects * @param {string} key - object key * @param {number} [errCode] - error code to match if applicable * @return {object | undefined} redirectInfo -- comprised of all of the ...
continue; } return undefined; } return undefined; } /** * extractRedirectInfo - convert location saved from x-amz-website header to * same format as redirectInfo saved from a put bucket website configuration * @param {string} location - location to redirect to * @return {object...
{ const redirectInfo = Object.assign({}, routingRules[i].getRedirect()); return redirectInfo; }
conditional_block
dbtool.py
#!/usr/bin/env python2 from __future__ import print_function import sys import os import urllib import argparse import xml.etree.ElementTree as ET def warn(*msgs): for x in msgs: print('[WARNING]:', x, file=sys.stderr) class PDBTM: def __init__(self, filename): #self.tree = ET.parse(filename) #self.root = self...
#http://pdbtm.enzim.hu/data/pdbtmall
random_line_split
dbtool.py
#!/usr/bin/env python2 from __future__ import print_function import sys import os import urllib import argparse import xml.etree.ElementTree as ET def warn(*msgs): for x in msgs: print('[WARNING]:', x, file=sys.stderr) class PDBTM: def __init__(self, filename): #self.tree = ET.parse(filename) #self.root = self...
(prefix='.'): if not prefix.endswith('/'): prefix += '/' print('Fetching database...', file=sys.stderr) db = urllib.urlopen('http://pdbtm.enzim.hu/data/pdbtmall') print('Saving database...', file=sys.stderr) f = open('%s/pdbtmall' % prefix, 'w') for l in db: f.write(l) #f.write(db.read()) db.close() f.close() ...
get_database
identifier_name
dbtool.py
#!/usr/bin/env python2 from __future__ import print_function import sys import os import urllib import argparse import xml.etree.ElementTree as ET def warn(*msgs):
class PDBTM: def __init__(self, filename): #self.tree = ET.parse(filename) #self.root = self.tree.getroot() def strsum(l): s = '' for x in l: s += x.rstrip() + '\n' return s f = open(filename) s = [] for l in f: s.append(l) #s = strsum(s[1:-1]).strip() s = strsum(s).strip() self.root = ET...
for x in msgs: print('[WARNING]:', x, file=sys.stderr)
identifier_body
dbtool.py
#!/usr/bin/env python2 from __future__ import print_function import sys import os import urllib import argparse import xml.etree.ElementTree as ET def warn(*msgs): for x in msgs: print('[WARNING]:', x, file=sys.stderr) class PDBTM: def __init__(self, filename): #self.tree = ET.parse(filename) #self.root = self...
for entry in zip(pdbids, entries): f = open(prefix + entry[0] + '.xml', 'w') f.write(entry[1]) f.close() if __name__ == '__main__': parser = argparse.ArgumentParser(description='Manages PDBTM databases. Automatically fetches the PDBTM database if no options are specified. Run without any arguments, dbtool ...
os.mkdir(prefix)
conditional_block
raft_client.rs
WriteFlags::default().buffer_hint(self.overflowing.is_some()), )); self.size = 0; if let Some(more) = self.overflowing.take() { self.push(more); } res } } /// A buffer for non-batch RaftMessage. struct MessageBuffer { batch: VecDeque<RaftMessage>, } impl M...
#[inline] fn flush(&mut self, sender: &mut ClientCStreamSender<RaftMessage>) -> grpcio::Result<()> { if let Some(msg) = self.batch.pop_front() { Pin::new(sender).start_send(( msg, WriteFlags::default().buffer_hint(!self.batch.is_empty()), )) ...
{ self.batch.is_empty() }
identifier_body
raft_client.rs
(&self) { self.connected.store(false, Ordering::SeqCst); } /// Wakes up consumer to retrive message. fn notify(&self) { if !self.buf.is_empty() { let t = self.waker.lock().unwrap().take(); if let Some(t) = t { t.wake(); } } } ...
disconnect
identifier_name
raft_client.rs
WriteFlags::default().buffer_hint(self.overflowing.is_some()), )); self.size = 0; if let Some(more) = self.overflowing.take() { self.push(more); } res } } /// A buffer for non-batch RaftMessage. struct MessageBuffer { batch: VecDeque<RaftMessage>, } impl M...
} let router = &self.router; router.broadcast_unreachable(self.store_id); } } impl<R, M, B, E> Future for RaftCall<R, M, B, E> where R: RaftStoreRouter<E> + Unpin + 'static, B: Buffer<OutputMessage = M> + Unpin, E: KvEngine, { type Output = (); fn poll(mut self: Pin<&mu...
let _ = tx.send(()); return; }
random_line_split
into_stream.rs
use core::pin::Pin; use futures_core::stream::{FusedStream, Stream, TryStream}; use futures_core::task::{Context, Poll}; #[cfg(feature = "sink")] use futures_sink::Sink; use pin_utils::unsafe_pinned; /// Stream for the [`into_stream`](super::TryStreamExt::into_stream) method. #[derive(Debug)] #[must_use = "streams do ...
fn size_hint(&self) -> (usize, Option<usize>) { self.stream.size_hint() } } // Forwarding impl of Sink from the underlying stream #[cfg(feature = "sink")] impl<S: Sink<Item>, Item> Sink<Item> for IntoStream<S> { type Error = S::Error; delegate_sink!(stream, Item); }
{ self.stream().try_poll_next(cx) }
identifier_body
into_stream.rs
use core::pin::Pin; use futures_core::stream::{FusedStream, Stream, TryStream}; use futures_core::task::{Context, Poll}; #[cfg(feature = "sink")] use futures_sink::Sink; use pin_utils::unsafe_pinned; /// Stream for the [`into_stream`](super::TryStreamExt::into_stream) method. #[derive(Debug)] #[must_use = "streams do ...
<St> { stream: St, } impl<St> IntoStream<St> { unsafe_pinned!(stream: St); #[inline] pub(super) fn new(stream: St) -> Self { IntoStream { stream } } /// Acquires a reference to the underlying stream that this combinator is /// pulling from. pub fn get_ref(&self) -> &St { ...
IntoStream
identifier_name
into_stream.rs
use core::pin::Pin; use futures_core::stream::{FusedStream, Stream, TryStream}; use futures_core::task::{Context, Poll}; #[cfg(feature = "sink")] use futures_sink::Sink; use pin_utils::unsafe_pinned; /// Stream for the [`into_stream`](super::TryStreamExt::into_stream) method. #[derive(Debug)] #[must_use = "streams do ...
fn size_hint(&self) -> (usize, Option<usize>) { self.stream.size_hint() } } // Forwarding impl of Sink from the underlying stream #[cfg(feature = "sink")] impl<S: Sink<Item>, Item> Sink<Item> for IntoStream<S> { type Error = S::Error; delegate_sink!(stream, Item); }
cx: &mut Context<'_>, ) -> Poll<Option<Self::Item>> { self.stream().try_poll_next(cx) }
random_line_split
basic_shape.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! CSS handling for the computed value of //! [`basic-shape`][basic-shape]s //! //! [basic-shape]: https://drafts...
<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { dest.write_str("ellipse(")?; if (self.semiaxis_x, self.semiaxis_y) != Default::default() { self.semiaxis_x.to_css(dest)?; dest.write_str(" ")?; self.semiaxis_y.to_css(dest)?; ...
to_css
identifier_name
basic_shape.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! CSS handling for the computed value of //! [`basic-shape`][basic-shape]s //! //! [basic-shape]: https://drafts...
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { dest.write_str("circle(")?; self.radius.to_css(dest)?; dest.write_str(" at ")?; self.position.to_css(dest)?; dest.write_str(")") } } impl ToCss for Ellipse { fn to_css<W>(&s...
impl ToCss for Circle {
random_line_split
basic_shape.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! CSS handling for the computed value of //! [`basic-shape`][basic-shape]s //! //! [basic-shape]: https://drafts...
dest.write_str("at ")?; self.position.to_css(dest)?; dest.write_str(")") } }
{ self.semiaxis_x.to_css(dest)?; dest.write_str(" ")?; self.semiaxis_y.to_css(dest)?; dest.write_str(" ")?; }
conditional_block
basic_shape.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! CSS handling for the computed value of //! [`basic-shape`][basic-shape]s //! //! [basic-shape]: https://drafts...
}
{ dest.write_str("ellipse(")?; if (self.semiaxis_x, self.semiaxis_y) != Default::default() { self.semiaxis_x.to_css(dest)?; dest.write_str(" ")?; self.semiaxis_y.to_css(dest)?; dest.write_str(" ")?; } dest.write_str("at ")?; self.po...
identifier_body
lib.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/. */ #![comment = "The Servo Parallel Browser Project"] #![license = "MPL"] #![feature(globs, macro_rules)] #![deny(u...
extern crate string_cache_macros; #[phase(plugin)] extern crate lazy_static; extern crate "util" as servo_util; // Public API pub use media_queries::{Device, Screen}; pub use stylesheets::{Stylesheet, iter_font_face_rules}; pub use selector_matching::{Stylist, StylesheetOrigin, UserAgentOrigin, AuthorOrigin, UserOr...
random_line_split
test-utils.py
# -*- coding: utf8 -*- import base64 import hashlib import io import nose import requests import aliyunauth.utils import aliyunauth.consts def test_cal_b64md5(): s_data = b"foo" l_data = b"bar" * aliyunauth.consts.MD5_CHUNK_SIZE # normal data, None nose.tools.eq_(aliyunauth.utils.cal_b64md5(None), ...
aliyunauth.utils.cal_b64md5(io.StringIO(l_data.decode("utf8"))), b64md5(l_data) ) def test_to_bytes(): nose.tools.ok_(isinstance( aliyunauth.utils.to_bytes(u"foo"), requests.compat.bytes )) nose.tools.ok_(isinstance( aliyunauth.utils.to_bytes(b"foo"), re...
nose.tools.eq_(
random_line_split
test-utils.py
# -*- coding: utf8 -*- import base64 import hashlib import io import nose import requests import aliyunauth.utils import aliyunauth.consts def
(): s_data = b"foo" l_data = b"bar" * aliyunauth.consts.MD5_CHUNK_SIZE # normal data, None nose.tools.eq_(aliyunauth.utils.cal_b64md5(None), None) def b64md5(data): return base64.b64encode(hashlib.md5(data).digest()).decode("utf8") # normal data, small size, bytes nose.tools.eq_(al...
test_cal_b64md5
identifier_name
test-utils.py
# -*- coding: utf8 -*- import base64 import hashlib import io import nose import requests import aliyunauth.utils import aliyunauth.consts def test_cal_b64md5(): s_data = b"foo" l_data = b"bar" * aliyunauth.consts.MD5_CHUNK_SIZE # normal data, None nose.tools.eq_(aliyunauth.utils.cal_b64md5(None), ...
est_percent_encode(): nose.tools.eq_( aliyunauth.utils.percent_encode([("福 棒", "foo+bar"), ("none", None)]), "%E7%A6%8F%20%E6%A3%92=foo%2Bbar" ) nose.tools.eq_( aliyunauth.utils.percent_encode([("foo", "福"), ("bar", "棒")], True), "bar=%E6%A3%92&foo=%E7%A6%8F" )
.tools.eq_( aliyunauth.utils.percent_quote(u"福棒 &?/*~=+foo\""), "%E7%A6%8F%E6%A3%92%20%26%3F%2F%2A~%3D%2Bfoo%22" ) def t
identifier_body
test-system.js
/* 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 strict"; const runtime = require("sdk/system/runtime"); const system = require("sdk/system"); exports["test ...
assert.ok( system.architecture === null || typeof(system.architecture) === "string", "system.architecture is string or null if not supported by platform" ); assert.ok( system.compiler === null || typeof(system.compiler) === "string", "system.compiler is string or null if not supported by platfo...
{ assert.equal( runtime.XPCOMABI.indexOf(system.compiler), runtime.XPCOMABI.length - system.compiler.length, "system.compiler is trailing substring of runtime.XPCOMABI" ); }
conditional_block
test-system.js
/* 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 strict"; const runtime = require("sdk/system/runtime"); const system = require("sdk/system"); exports["test ...
assert.ok( system.architecture === null || typeof(system.architecture) === "string", "system.architecture is string or null if not supported by platform" ); assert.ok( system.compiler === null || typeof(system.compiler) === "string", "system.compiler is string or null if not supported by platform...
"system.compiler is trailing substring of runtime.XPCOMABI" ); }
random_line_split
bip65-cltv-p2p.py
#!/usr/bin/env python2 # # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.test_framework import ComparisonTestFramework from test_framework.util import * from test_framework.mininode import CTransaction, N...
def create_transaction(self, node, coinbase, to_address, amount): from_txid = node.getblock(coinbase)['tx'][0] inputs = [{ "txid" : from_txid, "vout" : 0}] outputs = { to_address : amount } rawtx = node.createrawtransaction(inputs, outputs) signresult = node.signrawtransact...
test = TestManager(self, self.options.tmpdir) test.add_all_connections(self.nodes) NetworkThread().start() # Start up network handling in another thread test.run()
identifier_body
bip65-cltv-p2p.py
#!/usr/bin/env python2 # # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.test_framework import ComparisonTestFramework from test_framework.util import * from test_framework.mininode import CTransaction, N...
block.solve() test_blocks.append([block, True]) self.last_block_time += 1 self.tip = block.sha256 yield TestInstance(test_blocks, sync_every_block=False) ''' Mine 1 old version block ''' block = create_block(self.tip, create_coinbase(1), self.last...
test_blocks = [] for i in xrange(199): block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1) block.nVersion = 4 block.rehash()
random_line_split
bip65-cltv-p2p.py
#!/usr/bin/env python2 # # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.test_framework import ComparisonTestFramework from test_framework.util import * from test_framework.mininode import CTransaction, N...
(self): # Must set the blockversion for this test self.nodes = start_nodes(1, self.options.tmpdir, extra_args=[['-debug', '-whitelist=127.0.0.1', '-blockversion=3']], binary=[self.options.testbinary]) def run_test(self): test...
setup_network
identifier_name
bip65-cltv-p2p.py
#!/usr/bin/env python2 # # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.test_framework import ComparisonTestFramework from test_framework.util import * from test_framework.mininode import CTransaction, N...
yield TestInstance(test_blocks, sync_every_block=False) ''' Mine 1 old version block ''' block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1) block.nVersion = 3 block.rehash() block.solve() self.last_block_time += 1 self.tip = blo...
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1) block.nVersion = 4 block.rehash() block.solve() test_blocks.append([block, True]) self.last_block_time += 1 self.tip = block.sha256
conditional_block
createWriteStreamSpec.js
const Promise = require('bluebird'); const util = require('util');
const _path = require('path'); const _ = require('lodash'); describe("FileUtil", function () { before(function () { var variables = this; variables.tempDir = TestUtil.createDirectory(); }); after(function () { var variables = this; TestUtil.fs.rm({path: variables.tempDir.par...
const FileUtil = require('../../lib/index').FileUtil; const fs = require('fs');
random_line_split
trace.rs
. The GC calls `_trace` defined in `FooBinding` during the marking //! phase. (This happens through `JSClass.trace` for non-proxy bindings, and //! through `ProxyTraps.trace` otherwise.) //! 2. `_trace` calls `Foo::trace()` (an implementation of `JSTraceable`). //! This is typically derived via a `#[dom_struct...
} no_jsmanaged_fields!(bool, f32, f64, String, Url); no_jsmanaged_fields!(usize, u8, u16, u32, u64); no_jsmanaged_fields!(isize, i8, i16, i32, i64); no_jsmanaged_fields!(Sender<T>); no_jsmanaged_fields!(Receiver<T>); no_jsmanaged_fields!(Rect<T>); no_jsmanaged_fields!(ImageCacheTask, ScriptControlChan); no_jsmanaged...
{ let (ref a, ref b) = *self; a.trace(trc); b.trace(trc); }
identifier_body
trace.rs
. The GC calls `_trace` defined in `FooBinding` during the marking //! phase. (This happens through `JSClass.trace` for non-proxy bindings, and //! through `ProxyTraps.trace` otherwise.) //! 2. `_trace` calls `Foo::trace()` (an implementation of `JSTraceable`). //! This is typically derived via a `#[dom_struct...
unsafe { let name = CString::from_slice(description.as_bytes()); (*tracer).debugPrinter = None; (*tracer).debugPrintIndex = -1; (*tracer).debugPrintArg = name.as_ptr() as *const libc::c_void; debug!("tracing value {}", description); JS_CallTracer(tracer, val.to_gcth...
{ return; }
conditional_block
trace.rs
. The GC calls `_trace` defined in `FooBinding` during the marking //! phase. (This happens through `JSClass.trace` for non-proxy bindings, and //! through `ProxyTraps.trace` otherwise.) //! 2. `_trace` calls `Foo::trace()` (an implementation of `JSTraceable`). //! This is typically derived via a `#[dom_struct...
(&self, trc: *mut JSTracer) { self.get().trace(trc) } } impl JSTraceable for *mut JSObject { fn trace(&self, trc: *mut JSTracer) { trace_object(trc, "object", *self); } } impl JSTraceable for JSVal { fn trace(&self, trc: *mut JSTracer) { trace_jsval(trc, "val", *self); } } ...
trace
identifier_name
trace.rs
1. The GC calls `_trace` defined in `FooBinding` during the marking //! phase. (This happens through `JSClass.trace` for non-proxy bindings, and //! through `ProxyTraps.trace` otherwise.) //! 2. `_trace` calls `Foo::trace()` (an implementation of `JSTraceable`). //! This is typically derived via a `#[dom_struc...
// if e.trace() is a no-op (e.g it is an no_jsmanaged_fields type) impl<T: JSTraceable> JSTraceable for Vec<T> { #[inline] fn trace(&self, trc: *mut JSTracer) { for e in self.iter() { e.trace(trc); } } } // XXXManishearth Check if the following three are optimized to no-ops // i...
// XXXManishearth Check if the following three are optimized to no-ops
random_line_split
GroupView.js
import template from './group.hbs'; import LayoutBehavior from '../behaviors/LayoutBehavior'; import MenuButtonView from './MenuButtonView'; const defaultOptions = ({ view }) => ({ collapsed: false, collapsible: Boolean(view) }); const classes = { CLASS_NAME: 'layout-group', COLLAPSED_CLASS: 'group-co...
() { const view = this.model.get('view'); if (view) { this.showChildView('containerRegion', view); } else { this.ui.containerRegion[0].setAttribute('hidden', ''); } this.__updateState(); this.__onCollapsedChange(); // TODO: toolbar? ...
onRender
identifier_name
GroupView.js
import template from './group.hbs'; import LayoutBehavior from '../behaviors/LayoutBehavior'; import MenuButtonView from './MenuButtonView'; const defaultOptions = ({ view }) => ({ collapsed: false, collapsible: Boolean(view) }); const classes = { CLASS_NAME: 'layout-group', COLLAPSED_CLASS: 'group-co...
events: { 'click @ui.toggleCollapseButtons': 'onClickToggleButton', 'click @ui.menuRegion': 'onMenuClick', 'click @ui.restore': '__onRestore' }, modelEvents: { 'change:isMaximized': '__onMaximizedChange' }, onRender() { const view = this.model.get('view'); ...
restore: '.js-restore' },
random_line_split
GroupView.js
import template from './group.hbs'; import LayoutBehavior from '../behaviors/LayoutBehavior'; import MenuButtonView from './MenuButtonView'; const defaultOptions = ({ view }) => ({ collapsed: false, collapsible: Boolean(view) }); const classes = { CLASS_NAME: 'layout-group', COLLAPSED_CLASS: 'group-co...
, __execute(id) { switch (id) { case menuItemsIds.maximize: this.__onMaximize(); break; default: break; } }, onMenuClick() { return false; }, __onRestore() { Core.services.WindowService.closeEl...
{ return [ { id: menuItemsIds.maximize, icon: 'window-maximize', name: Localizer.get('CORE.LAYOUT.GROUPLAYOUT.MENU.MAXIMIZE') } ]; }
identifier_body
GroupView.js
import template from './group.hbs'; import LayoutBehavior from '../behaviors/LayoutBehavior'; import MenuButtonView from './MenuButtonView'; const defaultOptions = ({ view }) => ({ collapsed: false, collapsible: Boolean(view) }); const classes = { CLASS_NAME: 'layout-group', COLLAPSED_CLASS: 'group-co...
}, toggleCollapse(collapse = !this.model.get('collapsed')) { if (!this.model.get('collapsible')) { return; } this.model.set('collapsed', collapse); }, __onCollapsedChange(model = this.model, collapsed = this.model.get('collapsed')) { this.$el.toggleClass(cl...
{ this.toggleCollapse(); }
conditional_block
tokens.py
""" Based on :mod:`django.contrib.auth.tokens`. Supports the following settings: :setting:`WALDO_REGISTRATION_TIMEOUT_DAYS` The number of days a registration link will be valid before expiring. Default: 1. :setting:`WALDO_EMAIL_TIMEOUT_DAYS` The number of days an email change link will be valid before expiring. Def...
# Check that the timestamp is within limit if (self._num_days(self._today()) - ts) > REGISTRATION_TIMEOUT_DAYS: return False return True def _make_token_with_timestamp(self, user, timestamp): ts_b36 = int_to_base36(timestamp) # By hashing on the internal state of the user and using state that is ...
"""Check that a registration token is correct for a given user.""" # If the user is active, the hash can't be valid. if user.is_active: return False # Parse the token try: ts_b36, hash = token.split('-') except ValueError: return False try: ts = base36_to_int(ts_b36) except ValueError: ...
identifier_body
tokens.py
""" Based on :mod:`django.contrib.auth.tokens`. Supports the following settings: :setting:`WALDO_REGISTRATION_TIMEOUT_DAYS` The number of days a registration link will be valid before expiring. Default: 1. :setting:`WALDO_EMAIL_TIMEOUT_DAYS` The number of days an email change link will be valid before expiring. Def...
if self._make_token_with_timestamp(user, email, ts) != token: return False # Check that the timestamp is within limit if (self._num_days(self._today()) - ts) > EMAIL_TIMEOUT_DAYS: return False return True def _make_token_with_timestamp(self, user, email, timestamp): ts_b36 = int_to_base36(times...
ts = base36_to_int(ts_b36) except ValueError: return False # Check that the timestamp and uid have not been tampered with.
random_line_split
tokens.py
""" Based on :mod:`django.contrib.auth.tokens`. Supports the following settings: :setting:`WALDO_REGISTRATION_TIMEOUT_DAYS` The number of days a registration link will be valid before expiring. Default: 1. :setting:`WALDO_EMAIL_TIMEOUT_DAYS` The number of days an email change link will be valid before expiring. Def...
# Check that the timestamp is within limit if (self._num_days(self._today()) - ts) > REGISTRATION_TIMEOUT_DAYS: return False return True def _make_token_with_timestamp(self, user, timestamp): ts_b36 = int_to_base36(timestamp) # By hashing on the internal state of the user and using state that ...
return False
conditional_block
tokens.py
""" Based on :mod:`django.contrib.auth.tokens`. Supports the following settings: :setting:`WALDO_REGISTRATION_TIMEOUT_DAYS` The number of days a registration link will be valid before expiring. Default: 1. :setting:`WALDO_EMAIL_TIMEOUT_DAYS` The number of days an email change link will be valid before expiring. Def...
(PasswordResetTokenGenerator): """Strategy object used to generate and check tokens for the user registration mechanism.""" def check_token(self, user, token): """Check that a registration token is correct for a given user.""" # If the user is active, the hash can't be valid. if user.is_active: return Fals...
RegistrationTokenGenerator
identifier_name
debug_view.rs
use crate::logger; use crate::theme; use crate::view::View; use crate::Printer; use crate::Vec2; use unicode_width::UnicodeWidthStr; /// View used for debugging, showing logs. pub struct DebugView { // TODO: wrap log lines if needed, and save the line splits here. } impl DebugView { /// Creates a new DebugVi...
// TODO: customizable time format? (24h/AM-PM) printer.print( (0, i), &format!( "{} | [ ] {}", record.time.with_timezone(&chrono::Local).format("%T%.3f"), record.message ), ...
for (i, record) in logs.iter().skip(skipped).enumerate() { // TODO: Apply style to message? (Ex: errors in bold?)
random_line_split
debug_view.rs
use crate::logger; use crate::theme; use crate::view::View; use crate::Printer; use crate::Vec2; use unicode_width::UnicodeWidthStr; /// View used for debugging, showing logs. pub struct DebugView { // TODO: wrap log lines if needed, and save the line splits here. } impl DebugView { /// Creates a new DebugVi...
}
{ // Uh? }
identifier_body
debug_view.rs
use crate::logger; use crate::theme; use crate::view::View; use crate::Printer; use crate::Vec2; use unicode_width::UnicodeWidthStr; /// View used for debugging, showing logs. pub struct DebugView { // TODO: wrap log lines if needed, and save the line splits here. } impl DebugView { /// Creates a new DebugVi...
(&self, printer: &Printer) { let logs = logger::LOGS.lock().unwrap(); // Only print the last logs, so skip what doesn't fit let skipped = logs.len().saturating_sub(printer.size.y); for (i, record) in logs.iter().skip(skipped).enumerate() { // TODO: Apply style to message? (E...
draw
identifier_name
poll.rs
/// A macro. #[macro_export] macro_rules! try_poll { ($e:expr) => (match $e { $crate::Poll::NotReady => return $crate::Poll::NotReady, $crate::Poll::Ok(t) => Ok(t), $crate::Poll::Err(e) => Err(e), }) } /// Possible return values from the `Future::poll` method. #[derive(Copy, Clone, Deb...
} impl<T, E> From<Result<T, E>> for Poll<T, E> { fn from(r: Result<T, E>) -> Poll<T, E> { match r { Ok(t) => Poll::Ok(t), Err(t) => Poll::Err(t), } } }
{ match self { Poll::Ok(t) => Ok(t), Poll::Err(t) => Err(t), Poll::NotReady => panic!("unwrapping a Poll that wasn't ready"), } }
identifier_body
poll.rs
/// A macro. #[macro_export] macro_rules! try_poll { ($e:expr) => (match $e { $crate::Poll::NotReady => return $crate::Poll::NotReady, $crate::Poll::Ok(t) => Ok(t), $crate::Poll::Err(e) => Err(e), }) } /// Possible return values from the `Future::poll` method. #[derive(Copy, Clone, Debu...
Ok(T), /// Indicates that the future has failed, and this error is what the future /// failed with. Err(E), } impl<T, E> Poll<T, E> { /// Change the success type of this `Poll` value with the closure provided pub fn map<F, U>(self, f: F) -> Poll<U, E> where F: FnOnce(T) -> U { ...
/// what the future completed with.
random_line_split