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
router_module.ts
" button. * Use this option to configure the behavior when navigating to the * current URL. Default is 'ignore'. */ onSameUrlNavigation?: 'reload'|'ignore'; /** * Configures if the scroll position needs to be restored when navigating back. * * * 'disabled'- (Default) Does nothing. Scroll position...
* pauses. It waits for the hook to be resolved. We then resolve it only in a bootstrap listener. */ @Injectable() export class RouterInitializer implements OnDestroy { private initNavigation = false;
random_line_split
router_module.ts
data, and resolved data from parent to child * routes. By default ('emptyOnly'), inherits parent parameters only for * path-less or component-less routes. * * Set to 'always' to enable unconditional inheritance of parent parameters. * * Note that when dealing with matrix parameters, "parent" refers t...
return r.bootstrapListener.bind(r); }
identifier_body
router_module.ts
navigation starts after the root component has been created. * The bootstrap is not blocked on the completion of the initial navigation. When set to * `disabled`, the initial navigation is not performed. The location listener is set up before the * root component gets created. Use if there is a reason to have...
router.onSameUrlNavigation = opts.onSameUrlNavigation; }
conditional_block
branchify.rs
#![macro_use] use std::str::Chars; use std::vec::Vec; use std::io::IoResult; use std::iter::repeat; use std::ascii::AsciiExt; #[derive(Clone)] pub struct ParseBranch { matches: Vec<u8>, result: Option<String>, children: Vec<ParseBranch>, } impl ParseBranch { fn new() -> ParseBranch { ParseBra...
go_down_moses(&mut branch.children[i], chariter, result, case_sensitive); }, None => { assert!(branch.result.is_none()); branch.result = Some(String::from_str(result)); }, } } ; for &(key, result) in options.iter() { ...
{ match chariter.next() { Some(c) => { let first_case = if case_sensitive { c as u8 } else { c.to_ascii_uppercase() as u8 }; for next_branch in branch.children.iter_mut() { if next_branch.matches[0] == first_case { go_down_m...
identifier_body
branchify.rs
#![macro_use] use std::str::Chars; use std::vec::Vec; use std::io::IoResult; use std::iter::repeat; use std::ascii::AsciiExt; #[derive(Clone)] pub struct ParseBranch { matches: Vec<u8>, result: Option<String>, children: Vec<ParseBranch>, } impl ParseBranch { fn new() -> ParseBranch { ParseBra...
result: None, children: Vec::new() } } } pub fn branchify(options: &[(&str, &str)], case_sensitive: bool) -> Vec<ParseBranch> { let mut root = ParseBranch::new(); fn go_down_moses(branch: &mut ParseBranch, mut chariter: Chars, result: &str, case_sensitive: bool) { m...
random_line_split
branchify.rs
#![macro_use] use std::str::Chars; use std::vec::Vec; use std::io::IoResult; use std::iter::repeat; use std::ascii::AsciiExt; #[derive(Clone)] pub struct ParseBranch { matches: Vec<u8>, result: Option<String>, children: Vec<ParseBranch>, } impl ParseBranch { fn
() -> ParseBranch { ParseBranch { matches: Vec::new(), result: None, children: Vec::new() } } } pub fn branchify(options: &[(&str, &str)], case_sensitive: bool) -> Vec<ParseBranch> { let mut root = ParseBranch::new(); fn go_down_moses(branch: &mut ParseB...
new
identifier_name
branchify.rs
#![macro_use] use std::str::Chars; use std::vec::Vec; use std::io::IoResult; use std::iter::repeat; use std::ascii::AsciiExt; #[derive(Clone)] pub struct ParseBranch { matches: Vec<u8>, result: Option<String>, children: Vec<ParseBranch>, } impl ParseBranch { fn new() -> ParseBranch { ParseBra...
, } }; for &(key, result) in options.iter() { go_down_moses(&mut root, key.chars(), result, case_sensitive); } root.children } macro_rules! branchify( (case sensitive, $($key:expr => $value:ident),*) => ( ::branchify::branchify(&[$(($key, stringify!($value))),*], true) ...
{ assert!(branch.result.is_none()); branch.result = Some(String::from_str(result)); }
conditional_block
speech.js
slice(0); for (var i = 0; i < blockTypes.length; i++) { if (blockTypeMap.containsKey(blockTypes[i])) { blockTypes[i] = blockTypeMap.get(blockTypes[i]); } } return this.corrector_.correct(speech, blockIds, blockValuesetMap, blockTypes); }; /** * Restarts the listening for a new utterance. * @priva...
random_line_split
dcf.py
#!/usr/bin/python import sys sys.path.append('/var/www/html/valumodel.com/scripts/dcf') from calc_dcf import calc_dcf def create_dcf(req, tax_rate, growth_rate_1_year_out, sga_of_sales, da_of_sales, capex_of_sales, nwc_of_sales, levered_beta, current_yield, exit_multiple, ticker): assumptions = {} try: assumption...
return calc_dcf(assumptions, ticker.upper())
return '<!doctype html><html><body><h1>Invalid Ticker. Please try again.</h1></body></html>'
conditional_block
dcf.py
#!/usr/bin/python import sys sys.path.append('/var/www/html/valumodel.com/scripts/dcf') from calc_dcf import calc_dcf def create_dcf(req, tax_rate, growth_rate_1_year_out, sga_of_sales, da_of_sales, capex_of_sales, nwc_of_sales, levered_beta, current_yield, exit_multiple, ticker): assumptions = {} try: assumption...
except ValueError: return '<!doctype html><html><body><h1>Invalid DCF Input. Please try again.</h1></body></html>' ticker = ticker.split(' ')[0] if not ticker.isalnum(): return '<!doctype html><html><body><h1>Invalid Ticker. Please try again.</h1></body></html>' return calc_dcf(assump...
assumptions['Levered Beta'] = float(levered_beta) assumptions['Current Yield'] = float(current_yield)/100.0 assumptions['Exit Multiple'] = float(exit_multiple)
random_line_split
dcf.py
#!/usr/bin/python import sys sys.path.append('/var/www/html/valumodel.com/scripts/dcf') from calc_dcf import calc_dcf def
(req, tax_rate, growth_rate_1_year_out, sga_of_sales, da_of_sales, capex_of_sales, nwc_of_sales, levered_beta, current_yield, exit_multiple, ticker): assumptions = {} try: assumptions['Tax Rate'] = float(tax_rate)/100.0 assumptions['Growth Rate 1 year out'] = float(growth_rate_1_year_out)/100.0 as...
create_dcf
identifier_name
dcf.py
#!/usr/bin/python import sys sys.path.append('/var/www/html/valumodel.com/scripts/dcf') from calc_dcf import calc_dcf def create_dcf(req, tax_rate, growth_rate_1_year_out, sga_of_sales, da_of_sales, capex_of_sales, nwc_of_sales, levered_beta, current_yield, exit_multiple, ticker):
assumptions = {} try: assumptions['Tax Rate'] = float(tax_rate)/100.0 assumptions['Growth Rate 1 year out'] = float(growth_rate_1_year_out)/100.0 assumptions['SGA % of sales'] = float(sga_of_sales)/100.0 assumptions['D&A % of sales'] = float(da_of_sales)/100.0 assumptions['CAPEX...
identifier_body
vai-Vaii.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; fun...
export default [ 'vai-Vaii', [['AM', 'PM'], u, u], u, [ ['S', 'M', 'T', 'W', 'T', 'F', 'S'], [ 'ꕞꕌꔵ', 'ꗳꗡꘉ', 'ꕚꕞꕚ', 'ꕉꕞꕒ', 'ꕉꔤꕆꕢ', 'ꕉꔤꕀꕮ', 'ꔻꔬꔳ' ], u, u ], u, [ ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'], [ 'ꖨꖕꔞ', 'ꕒꕡ', 'ꕾꖺ', 'ꖢꖕ', 'ꖑꕱ', 'ꖱꘋ...
{ return 5; }
identifier_body
vai-Vaii.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; fun...
u, u ], u, [ ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'], [ 'ꖨꖕꔞ', 'ꕒꕡ', 'ꕾꖺ', 'ꖢꖕ', 'ꖑꕱ', 'ꖱꘋ', 'ꖱꕞ', 'ꗛꔕ', 'ꕢꕌ', 'ꕭꖃ', 'ꔞꘋ', 'ꖨꖕꗏ' ], [ 'ꖨꖕ ꕪꕴ ꔞꔀꕮꕊ', 'ꕒꕡꖝꖕ', 'ꕾꖺ', 'ꖢꖕ', 'ꖑꕱ', 'ꖱꘋ', 'ꖱꕞꔤ', 'ꗛꔕ', 'ꕢꕌ', 'ꕭꖃ', 'ꔞꘋꕔꕿ ꕸꖃꗏ', 'ꖨꖕ ꕪꕴ ꗏꖺꕮꕊ' ] ],...
'ꔻꔬꔳ' ],
random_line_split
vai-Vaii.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; fun...
(n: number): number { return 5; } export default [ 'vai-Vaii', [['AM', 'PM'], u, u], u, [ ['S', 'M', 'T', 'W', 'T', 'F', 'S'], [ 'ꕞꕌꔵ', 'ꗳꗡꘉ', 'ꕚꕞꕚ', 'ꕉꕞꕒ', 'ꕉꔤꕆꕢ', 'ꕉꔤꕀꕮ', 'ꔻꔬꔳ' ], u, u ], u, [ ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'], [ ...
plural
identifier_name
Options.js
var numSaves, _autoSaveChanges; module("TiddlyWiki options", { setup: function() { config.options.chkAutoSave = true; systemSettingSave = 0; _autoSaveChanges = autoSaveChanges; numSaves = 0; autoSaveChanges = function() { numSaves += 1; return _autoSaveChanges.apply(this, arguments); } }...
jQuery(document).ready(function(){
random_line_split
base.py
# Unix SMB/CIFS implementation.
# the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Pub...
# Copyright (C) Sean Dague <sdague@linux.vnet.ibm.com> 2011 # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by
random_line_split
base.py
# Unix SMB/CIFS implementation. # Copyright (C) Sean Dague <sdague@linux.vnet.ibm.com> 2011 # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your optio...
kwargs.update(optiongroups) H = kwargs.get("H", None) sambaopts = kwargs.get("sambaopts", None) credopts = kwargs.get("credopts", None) lp = sambaopts.get_loadparm() creds = credopts.get_credentials(lp, fallback_machine=True) samdb = SamDB(url=H, session_info=...
for option in option_group.option_list: if option.dest is not None: del kwargs[option.dest]
conditional_block
base.py
# Unix SMB/CIFS implementation. # Copyright (C) Sean Dague <sdague@linux.vnet.ibm.com> 2011 # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your optio...
(self, val, msg=""): self.assertIsNotNone(val, msg) def assertMatch(self, base, string, msg=""): self.assertTrue(string in base, msg) def randomName(self, count=8): """Create a random name, cap letters and numbers, and always starting with a letter""" name = random.choice(strin...
assertCmdFail
identifier_name
base.py
# Unix SMB/CIFS implementation. # Copyright (C) Sean Dague <sdague@linux.vnet.ibm.com> 2011 # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your optio...
def randomXid(self): # pick some hopefully unused, high UID/GID range to avoid interference # from the system the test runs on xid = random.randint(4711000, 4799000) return xid def assertWithin(self, val1, val2, delta, msg=""): """Assert that val1 is within delta of va...
name = random.choice(string.ascii_uppercase) name += random.choice(string.digits) name += random.choice(string.ascii_lowercase) name += ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase+ string.digits) for x in range(count - 3)) return name
identifier_body
test_production_order.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import unittest import frappe from frappe.utils import flt, get_datetime from erpnext.stock.doctype.purchase_receipt.test_purchase_receipt import set_p...
s.fiscal_year = "_Test Fiscal Year 2013" s.posting_date = "2013-01-02" s.insert() s.submit() # from wip to fg s = frappe.get_doc(make_stock_entry(pro_doc.name, "Manufacture", 4)) s.fiscal_year = "_Test Fiscal Year 2013" s.posting_date = "2013-01-03" s.insert() s.submit() self.assertEqual(frappe...
d.s_warehouse = "Stores - _TC"
conditional_block
test_production_order.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import unittest import frappe from frappe.utils import flt, get_datetime from erpnext.stock.doctype.purchase_receipt.test_purchase_receipt import set_p...
def test_make_time_log(self): from erpnext.manufacturing.doctype.production_order.production_order import make_time_log from frappe.utils import cstr from frappe.utils import time_diff_in_hours prod_order = frappe.get_doc({ "doctype": "Production Order", "production_item": "_Test FG Item 2", "bom_n...
from erpnext.manufacturing.doctype.production_order.production_order import StockOverProductionError pro_doc = self.check_planned_qty() test_stock_entry.make_stock_entry(item_code="_Test Item", target="_Test Warehouse - _TC", qty=100, incoming_rate=100) test_stock_entry.make_stock_entry(item_code="_Test Item ...
identifier_body
test_production_order.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import unittest import frappe from frappe.utils import flt, get_datetime from erpnext.stock.doctype.purchase_receipt.test_purchase_receipt import set_p...
prod_order.load_from_db() self.assertEqual(prod_order.operations[0].status, "Pending") self.assertEqual(flt(prod_order.operations[0].completed_qty), 0) self.assertEqual(flt(prod_order.operations[0].actual_operation_time), 0) self.assertEqual(flt(prod_order.operations[0].actual_operating_cost), 0) time_lo...
self.assertEqual(prod_order.operations[0].actual_operation_time, 60) self.assertEqual(prod_order.operations[0].actual_operating_cost, 100) time_log.cancel()
random_line_split
test_production_order.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import unittest import frappe from frappe.utils import flt, get_datetime from erpnext.stock.doctype.purchase_receipt.test_purchase_receipt import set_p...
(self): from erpnext.manufacturing.doctype.production_order.production_order import make_time_log from frappe.utils import cstr from frappe.utils import time_diff_in_hours prod_order = frappe.get_doc({ "doctype": "Production Order", "production_item": "_Test FG Item 2", "bom_no": "BOM/_Test FG Item 2/...
test_make_time_log
identifier_name
fixed_length_vec_glue.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 ...
// xfail-fast: check-fast screws up repr paths use std::repr; struct Struc { a: u8, b: [int, ..3], c: int } pub fn main() { let arr = [1,2,3]; let struc = Struc {a: 13u8, b: arr, c: 42}; let s = repr::repr_to_str(&struc); assert_eq!(s, ~"Struc{a: 13u8, b: [1, 2, 3], c: 42}"); }
// option. This file may not be copied, modified, or distributed // except according to those terms.
random_line_split
fixed_length_vec_glue.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 ...
{ a: u8, b: [int, ..3], c: int } pub fn main() { let arr = [1,2,3]; let struc = Struc {a: 13u8, b: arr, c: 42}; let s = repr::repr_to_str(&struc); assert_eq!(s, ~"Struc{a: 13u8, b: [1, 2, 3], c: 42}"); }
Struc
identifier_name
fixed_length_vec_glue.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let arr = [1,2,3]; let struc = Struc {a: 13u8, b: arr, c: 42}; let s = repr::repr_to_str(&struc); assert_eq!(s, ~"Struc{a: 13u8, b: [1, 2, 3], c: 42}"); }
identifier_body
setup.py
try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages setup( name='QSTK', version='0.1', description='Python toolkit for stocks', author='Tucker Balch', author_email='tuck...
'pytz==2012h', 'pandas==0.9.0', 'matplotlib==1.1.1', 'epydoc==3.0.1', ], tests_require=[ 'nose==1.2.1', 'coverage==3.5.3', 'pylint==0.26.0', 'pep8==1.3.3', 'pyflakes==0.5.0', ], setup_requires=[], packages=find_packages(exclude=...
'python-dateutil==2.1',
random_line_split
mediapipe_track_validator.py
# Lint as: python3 # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
def age_tracks(self): """Increases every tracks' age as well as staleness.""" for track in self._track_map.values(): track.age = track.age + 1 track.staleness = track.staleness + 1 def reset_tracks_with_detections(self, detections): """Resets the staleness of tracks if there are associate...
new_track = TrackWrapper( track=track, age=0, staleness=0, ) self._track_map[track.track_id] = new_track
conditional_block
mediapipe_track_validator.py
# Lint as: python3 # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
class MediaPipeTrackValidator: """Checks if an annotation is valid by measuring staleness. Each track is stored and aged. If a track box intersects with a new detection, then consider it an associated detection, and mark the track as fresh. If a track exists for longer than allowed_staleness, then filter t...
"""Wraps the tracking annotation with data only relevant to the validator.""" track: ObjectTrackingAnnotation age: int # How old this track is. staleness: int # How many iterations it has been since the last detection.
identifier_body
mediapipe_track_validator.py
# Lint as: python3 # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
(bbox1, bbox2): """Calculates the Intersection-Over-Union of two bounding boxes. IOU is a ratio for determining how much two bounding boxes match. Args: bbox1: The first bounding box. bbox2: The bounding box to compare with. Returns: The IOU as a float from 0.0 to 1.0 (1.0 being a perfect match.)...
calculate_iou
identifier_name
mediapipe_track_validator.py
# Lint as: python3 # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
self.age_tracks() self.reset_tracks_with_detections(detections) healthy_tracks = filter(lambda t: t.staleness <= self._allowed_staleness, self._track_map.values()) unwrapped_tracks = list(map(lambda t: t.track, healthy_tracks)) cancelled_tracks = filter(lambda t: t.stal...
self.update_tracks(managed_tracks)
random_line_split
hypergeometric.rs
extern crate rand; use crate::distribs::distribution::*; use crate::util::math::*; #[allow(non_snake_case)] #[allow(dead_code)] pub struct Hypergeometric { N: u64, m: u64, n: u64, } #[allow(dead_code)] impl Hypergeometric { pub fn new(total: u64, n_different: u64, n_picked: u64) -> Hypergeometric { ...
}
{ (0..x).fold(0.0f64, |sum, next| sum + self.pdf(next)) }
identifier_body
hypergeometric.rs
extern crate rand; use crate::distribs::distribution::*; use crate::util::math::*; #[allow(non_snake_case)] #[allow(dead_code)] pub struct Hypergeometric { N: u64, m: u64, n: u64, } #[allow(dead_code)] impl Hypergeometric { pub fn new(total: u64, n_different: u64, n_picked: u64) -> Hypergeometric { ...
} fn cdf(&self, x: u64) -> f64 { (0..x).fold(0.0f64, |sum, next| sum + self.pdf(next)) } }
} fn pdf(&self, x: u64) -> f64 { binomial_coeff(self.m, x) * binomial_coeff(self.N - self.m, self.N - x) / binomial_coeff(self.N, self.n)
random_line_split
hypergeometric.rs
extern crate rand; use crate::distribs::distribution::*; use crate::util::math::*; #[allow(non_snake_case)] #[allow(dead_code)] pub struct Hypergeometric { N: u64, m: u64, n: u64, } #[allow(dead_code)] impl Hypergeometric { pub fn new(total: u64, n_different: u64, n_picked: u64) -> Hypergeometric { ...
; let mut cum_prob: f64 = 0.0f64; let mut k: u64 = 0u64; for _ in 0..low_lim { cum_prob += self.pdf(k); if cum_prob > prob { break; } k += 1 } RandomVariable { value: Cell::new(k) } } fn mu(&self) -> f64...
{ self.m }
conditional_block
hypergeometric.rs
extern crate rand; use crate::distribs::distribution::*; use crate::util::math::*; #[allow(non_snake_case)] #[allow(dead_code)] pub struct Hypergeometric { N: u64, m: u64, n: u64, } #[allow(dead_code)] impl Hypergeometric { pub fn new(total: u64, n_different: u64, n_picked: u64) -> Hypergeometric { ...
(&self) -> f64 { let mean = self.mu(); let failure = ((self.N - self.m) as f64) / (self.N as f64); let remaining = ((self.N - self.n) as f64) / ((self.N - 1) as f64); (mean * failure * remaining).sqrt() } fn pdf(&self, x: u64) -> f64 { binomial_coeff(self.m, x) * binomi...
sigma
identifier_name
ja.js
OC.L10N.register( "notifications", { "Notifications" : "通知", "No notifications" : "通知なし", "Dismiss" : "閉じる", "Admin notifications" : "管理者向けの通知", "Unknown user session. It is not possible to set the option" : "不明なユーザーセッションです。オプションを設定することはできません。", "Option not supported" : "サポートされていないオプションで...
"You can choose to be notified about events via mail. Some events are informative, others require an action (like accept/decline). Select your preference below:" : "メールでイベントについての通知を受け取ることができます。イベントの中には有益なものや、(受け入れ・拒否などの)アクションが必要なものがあります。以下より選択してください:", "It was not possible to get your session. Please, try reloa...
"Hello," : "こんにちは、", "See <a href=\"%s\">%s</a> on %s for more information" : "詳細は <a href=\"%s\">%s</a> ( %s 内)を参照してください", "See %s on %s for more information" : "詳細は %s (%s 内)を参照してください", "Mail Notifications" : "メール通知",
random_line_split
graph.rs
_node(engine.default_input(1).unwrap()); //! let oscillator = graph.add_node(Oscillator::new(Sine).freq(440.0)); //! let filter = graph.add_node(Filter::new(LowPass(8000f32), 1)); //! let speaker = graph.add_node(engine.default_output(2).unwrap()); //! //! // Connect devices together //! graph.add_edge(microphone, 0, s...
).collect(); // While there are nodes with no input, we choose one, add it as the // next node in our topology, and remove all edges from that node. Any // nodes that lose their final edge are added to the edgeless set. loop { match no_inputs.pop_front() { ...
{ None }
conditional_block
graph.rs
//! channel, provided that connection does not create a cycle. //! //! A graph is initialized by adding each device as a node in the graph, and //! then specifying the edges between devices. The graph will automatically //! process the devices in order of their dependencies. //! //! # Example //! //! The following exa...
//! A container for audio devices in an acyclic graph. //! //! A graph can be used when many audio devices need to connect in complex //! topologies. It can connect each output channel of a device to any input
random_line_split
graph.rs
} } /// Adds a new device into the graph, with no connections. Returns /// a identifier that refers back to this device. pub fn add_node<D>(&mut self, device: D) -> AudioNodeIdx where D: 'static+AudioDevice { let node = AudioNode::new(device, &mut self.bus); let idx ...
test_direct_cycle
identifier_name
bwt.rs
[SA[i] - 1] if i == 0 { 0 } else { input[(i - 1) as usize] } }).collect() } // Takes a frequency map of bytes and generates the index of first occurrence // of each byte. fn generate_occurrence_index(map: &mut Vec<u32>) { let mut idx = 0; for i in 0..map.len() { let c = map[i]; map...
} let mut i = lf_vec[0] as usize; lf_vec[0] = 0; let mut counter = bwt_data.len() as u32 - 1; // Only difference is that we replace the LF indices with the lengths of prefix // from a particular position (in other words, the number of times // it would take us t...
{ let mut map = Vec::new(); let mut count = vec![0u32; bwt_data.len()]; let mut idx = 0; // generate the frequency map and forward frequency vector from BWT for i in &bwt_data { let value = insert(&mut map, *i); count[idx] = value; idx += 1; ...
identifier_body
bwt.rs
use nucleic_acid::FMIndex; /// /// let text = String::from("GCGTGCCCAGGGCACTGCCGCTGCAGGCGTAGGCATCGCATCACACGCGT"); /// let index = FMIndex::new(text.as_bytes()); /// /// // count the occurrences /// assert_eq!(0, index.count("CCCCC")); /// assert_eq!(3, index.count("TG")); /// /// // ... or get their positions /// asse...
random_line_split
bwt.rs
[SA[i] - 1] if i == 0 { 0 } else { input[(i - 1) as usize] } }).collect() } // Takes a frequency map of bytes and generates the index of first occurrence // of each byte. fn
(map: &mut Vec<u32>) { let mut idx = 0; for i in 0..map.len() { let c = map[i]; map[i] = idx; idx += c; } } /// Invert the BWT and generate the original data. /// /// ``` rust /// let text = String::from("Hello, world!"); /// let bw = nucleic_acid::bwt(text.as_bytes()); /// let ibw...
generate_occurrence_index
identifier_name
LocaleSwitch.js
/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/docume...
include : qx.locale.MTranslation, construct : function() { this.base(arguments); var manager = this.manager = qx.locale.Manager.getInstance(); // add dummy translations manager.addTranslation("en_QX", { "test one": "test one", "test two": "test two", "test Hello %1!": "test He...
{ extend : qx.test.mobile.MobileTestCase,
random_line_split
flags.js
/** */ function Flags(_flags) { "use strict"; var _init, _isValidFlag, _convertToBoolean, _setFlagGetterAndSetter, _getFlagValuesFromHash, _internalFlags = {}, _api = this; const REGEXP_HASHFLAG = /flags\[([A-Za-z0-9\-\_\&=]+)]/i; /************************* Validate *************************/ // I...
return bool; }; _getFlagValuesFromHash = function () { var hashFlags = {}, regexpResult; regexpResult = REGEXP_HASHFLAG.exec(location.hash); if (Array.isArray(regexpResult) && regexpResult.length === 2) { regexpResult[1] .split("&") .forEach(flagStr => { var key, value, parts; p...
{ throw new SyntaxError(); }
conditional_block
flags.js
/** */ function
(_flags) { "use strict"; var _init, _isValidFlag, _convertToBoolean, _setFlagGetterAndSetter, _getFlagValuesFromHash, _internalFlags = {}, _api = this; const REGEXP_HASHFLAG = /flags\[([A-Za-z0-9\-\_\&=]+)]/i; /************************* Validate *************************/ // If: The flags was called...
Flags
identifier_name
flags.js
/** */ function Flags(_flags) { "use strict"; var _init, _isValidFlag, _convertToBoolean, _setFlagGetterAndSetter, _getFlagValuesFromHash, _internalFlags = {}, _api = this; const REGEXP_HASHFLAG = /flags\[([A-Za-z0-9\-\_\&=]+)]/i; /************************* Validate *************************/ // I...
throw new SyntaxError(`Flags is not a function, use it as a constructor. Usage: var flags = new Flags({})`); } // If: The flags list is not defined. // Then: Throw an exception and prevent the API from being returned. if (typeof _flags === "undefined") { throw new SyntaxError(`The flags list is not defined. ...
random_line_split
flags.js
/** */ function Flags(_flags)
// If: The flags list is not defined. // Then: Throw an exception and prevent the API from being returned. if (typeof _flags === "undefined") { throw new SyntaxError(`The flags list is not defined. Pass an object to the constructor.`); } // If: The flags list is not an object. // Then: Throw an exception a...
{ "use strict"; var _init, _isValidFlag, _convertToBoolean, _setFlagGetterAndSetter, _getFlagValuesFromHash, _internalFlags = {}, _api = this; const REGEXP_HASHFLAG = /flags\[([A-Za-z0-9\-\_\&=]+)]/i; /************************* Validate *************************/ // If: The flags was called as a fun...
identifier_body
variable.py
else: os.symlink(src, dst) def getUserDir(): try: import pwd if not os.environ['HOME']: os.environ['HOME'] = sp(pwd.getpwuid(os.geteuid()).pw_dir) except: pass return sp(os.path.expanduser('~')) def getDownloadDir(): user_dir = getUserDir() # OSX...
for key in current_src: if key not in current_dst: current_dst[key] = current_src[key] else: if isDict(current_src[key]) and isDict(current_dst[key]): stack.append((current_dst[key], current_src[key])) elif isinstance(cu...
dst = a.copy() stack = [(dst, b)] while stack: current_dst, current_src = stack.pop()
random_line_split
variable.py
else: os.symlink(src, dst) def getUserDir(): try: import pwd if not os.environ['HOME']: os.environ['HOME'] = sp(pwd.getpwuid(os.geteuid()).pw_dir) except: pass return sp(os.path.expanduser('~')) def getDownloadDir(): user_dir = getUserDir() # OSX ...
(value): if isinstance(value, collections.Iterable): return value return [value] def getIdentifier(media): return media.get('identifier') or media.get('identifiers', {}).get('imdb') def getTitle(media_dict): try: try: return media_dict['title'] except: ...
toIterable
identifier_name
variable.py
Duplicates(seq): checked = [] for e in seq: if e not in checked: checked.append(e) return checked def flattenList(l): if isinstance(l, list): return sum(map(flattenList, l)) else: return l def md5(text): return hashlib.md5(ss(text)).hexdigest() def sha1(...
total_size += os.path.getsize(sp(os.path.join(dirpath, f)))
conditional_block
variable.py
else: os.symlink(src, dst) def getUserDir(): try: import pwd if not os.environ['HOME']: os.environ['HOME'] = sp(pwd.getpwuid(os.geteuid()).pw_dir) except: pass return sp(os.path.expanduser('~')) def getDownloadDir(): user_dir = getUserDir() # OSX ...
def getTitle(media_dict): try: try: return media_dict['title'] except: try: return media_dict['titles'][0] except: try: return media_dict['info']['titles'][0] except: try: ...
return media.get('identifier') or media.get('identifiers', {}).get('imdb')
identifier_body
transition.js
/*! * SeaUI: transition.js v1.0.0 * Copyright 2013-2014 chanh * Licensed under MIT(https://github.com/seaui/transition/blob/master/LICENSE) */ define("seaui/transition/1.0.0/transition",["jquery/jquery/1.10.1/jquery"],function(a){function b()
var c=a("jquery/jquery/1.10.1/jquery");c.fn.emulateTransitionEnd=function(a){var b=!1,d=this;c(this).one(c.support.transition.end,function(){b=!0});var e=function(){b||c(d).trigger(c.support.transition.end)};return setTimeout(e,a),this},c(function(){c.support.transition=b()})});
{var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}
identifier_body
transition.js
/*! * SeaUI: transition.js v1.0.0 * Copyright 2013-2014 chanh * Licensed under MIT(https://github.com/seaui/transition/blob/master/LICENSE) */ define("seaui/transition/1.0.0/transition",["jquery/jquery/1.10.1/jquery"],function(a){function
(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}var c=a("jquery/jquery/1.10.1/jquery");c.fn.emulateTransitionEnd=fu...
b
identifier_name
transition.js
* Licensed under MIT(https://github.com/seaui/transition/blob/master/LICENSE) */ define("seaui/transition/1.0.0/transition",["jquery/jquery/1.10.1/jquery"],function(a){function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitio...
/*! * SeaUI: transition.js v1.0.0 * Copyright 2013-2014 chanh
random_line_split
setup.py
if os.path.exists(mailmap): fp = open(mailmap, 'r') for l in fp: l = l.strip() if not l.startswith('#') and ' ' in l: canonical_email, alias = l.split(' ') mapping[alias] = canonical_email return mapping def canonicalize_emails(changelog,...
module_list = modules.keys() module_list.sort() autoindex_filename = os.path.join(source_dir, 'autoindex.rst') with open(autoindex_filename, 'w') as autoindex: autoindex.write(""".. toctree:: :maxdepth: 1 """) f...
if '.' not in pkg: os.path.walk(pkg, _find_modules, modules)
conditional_block
setup.py
if os.path.exists(mailmap): fp = open(mailmap, 'r') for l in fp: l = l.strip() if not l.startswith('#') and ' ' in l: canonical_email, alias = l.split(' ') mapping[alias] = canonical_email return mapping def canonicalize_emails(changelog,...
def _run_shell_command(cmd): output = subprocess.Popen(["/bin/sh", "-c", cmd], stdout=subprocess.PIPE) out = output.communicate() if len(out) == 0: return None if len(out[0].strip()) == 0: return None return out[0].strip() def _get_git_next_version_...
venv = os.environ.get('VIRTUAL_ENV', None) if venv is not None: with open("requirements.txt", "w") as req_file: output = subprocess.Popen(["pip", "-E", venv, "freeze", "-l"], stdout=subprocess.PIPE) requirements = output.communicate()[0].strip() ...
identifier_body
setup.py
if os.path.exists(mailmap): fp = open(mailmap, 'r') for l in fp: l = l.strip() if not l.startswith('#') and ' ' in l: canonical_email, alias = l.split(' ') mapping[alias] = canonical_email return mapping def canonicalize_emails(changelog,...
(): """Create AUTHORS file using git commits.""" jenkins_email = 'jenkins@review.openstack.org' old_authors = 'AUTHORS.in' new_authors = 'AUTHORS' if os.path.isdir('.git'): # don't include jenkins email address in AUTHORS file git_log_cmd = ("git log --format='%aN <%aE>' | sort -u | ...
generate_authors
identifier_name
setup.py
if os.path.exists(mailmap): fp = open(mailmap, 'r') for l in fp: l = l.strip() if not l.startswith('#') and ' ' in l: canonical_email, alias = l.split(' ') mapping[alias] = canonical_email return mapping def canonicalize_emails(changelog,...
def _get_git_current_tag(): return _run_shell_command("git tag --contains HEAD") def _get_git_tag_info(): return _run_shell_command("git describe --tags") def _get_git_post_version(): current_tag = _get_git_current_tag() if current_tag is not None: return current_tag else: tag_...
milestonever = "" post_version = _get_git_post_version() revno = post_version.split(".")[-1] return "%s~%s.%s%s" % (milestonever, datestamp, revno_prefix, revno)
random_line_split
azure_cleanup.py
import argparse import sys import traceback as tb from datetime import datetime from cfme.utils.path import log_path from cfme.utils.providers import list_provider_keys, get_mgmt def parse_cmd_line(): parser = argparse.ArgumentParser(argument_default=None) parser.add_argument('--nic-template', ...
else: report.write("No stacks older than \'{}\' days were found\n".format( days_old)) return 0 except Exception: report.write("Something bad happened during Azure cleanup\n") report.write(tb.format_exc()) ...
if provider_mgmt.is_stack_empty(stack): provider_mgmt.delete_stack(stack) report.write("Stack {} is empty - Removed\n".format(stack))
conditional_block
azure_cleanup.py
import argparse import sys import traceback as tb from datetime import datetime from cfme.utils.path import log_path from cfme.utils.providers import list_provider_keys, get_mgmt def
(): parser = argparse.ArgumentParser(argument_default=None) parser.add_argument('--nic-template', help='NIC Name template to be removed', default="test", type=str) parser.add_argument('--pip-template', help='PIP Name template to be removed', default="test", ty...
parse_cmd_line
identifier_name
azure_cleanup.py
import argparse import sys import traceback as tb from datetime import datetime from cfme.utils.path import log_path from cfme.utils.providers import list_provider_keys, get_mgmt def parse_cmd_line():
def azure_cleanup(nic_template, pip_template, days_old, output): with open(output, 'w') as report: report.write('azure_cleanup.py, NICs, PIPs and Stack Cleanup') report.write("\nDate: {}\n".format(datetime.now())) try: for provider_key in list_provider_keys('azure'): ...
parser = argparse.ArgumentParser(argument_default=None) parser.add_argument('--nic-template', help='NIC Name template to be removed', default="test", type=str) parser.add_argument('--pip-template', help='PIP Name template to be removed', default="test", type=str) ...
identifier_body
azure_cleanup.py
import argparse import sys import traceback as tb from datetime import datetime from cfme.utils.path import log_path from cfme.utils.providers import list_provider_keys, get_mgmt def parse_cmd_line(): parser = argparse.ArgumentParser(argument_default=None) parser.add_argument('--nic-template', ...
provider_mgmt = get_mgmt(provider_key) nic_list = provider_mgmt.list_free_nics(nic_template) report.write("----- Provider: {} -----\n".format(provider_key)) if nic_list: report.write("Removing Nics with the name \'{}\':\n".format(nic_te...
with open(output, 'w') as report: report.write('azure_cleanup.py, NICs, PIPs and Stack Cleanup') report.write("\nDate: {}\n".format(datetime.now())) try: for provider_key in list_provider_keys('azure'):
random_line_split
damagePattern.py
# ============================================================================= # Copyright (C) 2010 Diego Duclos # # This file is part of pyfa. # # pyfa 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 ...
eos.db.commit() lenImports = len(imports) if lenImports == 0: raise ImportError("No patterns found for import") if lenImports != num: raise ImportError("%d patterns imported from clipboard; %d had errors" % (num, num - lenImports)) def exportPatterns(self):...
eos.db.save(pattern)
conditional_block
damagePattern.py
# ============================================================================= # Copyright (C) 2010 Diego Duclos # # This file is part of pyfa. # # pyfa 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 ...
return es_DamagePattern.exportPatterns(*patterns)
patterns.sort(key=lambda p: p.name)
random_line_split
damagePattern.py
# ============================================================================= # Copyright (C) 2010 Diego Duclos # # This file is part of pyfa. # # pyfa 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 ...
(self, name): return eos.db.getDamagePattern(name) def newPattern(self, name): p = es_DamagePattern(0, 0, 0, 0) p.name = name eos.db.save(p) return p def renamePattern(self, p, newName): p.name = newName eos.db.save(p) def deletePattern(self, p): ...
getDamagePattern
identifier_name
damagePattern.py
# ============================================================================= # Copyright (C) 2010 Diego Duclos # # This file is part of pyfa. # # pyfa 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 ...
def getDamagePatternList(self): return eos.db.getDamagePatternList() def getDamagePattern(self, name): return eos.db.getDamagePattern(name) def newPattern(self, name): p = es_DamagePattern(0, 0, 0, 0) p.name = name eos.db.save(p) return p def renamePa...
if cls.instance is None: cls.instance = DamagePattern() return cls.instance
identifier_body
albums.rs
use std::collections::HashMap; use postgres::GenericConnection as PostgresConnection; use db::pg::RowsExtension; use library::Result; const MAX_TOP_ALBUMS: i64 = 10; #[derive(RustcEncodable)] struct Track { name: String, is_favorite: bool, scrobbles: Vec<i32>, } #[derive(RustcEncodable)] pub struct Alb...
pub fn total_albums(conn: &PostgresConnection) -> Result<i64> { Ok(try!(conn.query("SELECT COUNT(*) FROM albums", &[])).fetch_column()) }
random_line_split
albums.rs
use std::collections::HashMap; use postgres::GenericConnection as PostgresConnection; use db::pg::RowsExtension; use library::Result; const MAX_TOP_ALBUMS: i64 = 10; #[derive(RustcEncodable)] struct Track { name: String, is_favorite: bool, scrobbles: Vec<i32>, } #[derive(RustcEncodable)] pub struct Alb...
let name: String = rows.get(0).get("name"); let mut tracks = HashMap::<i32, Track>::new(); let query = "SELECT id, name, is_favorite FROM tracks WHERE album_id = $1"; for row in &try!(conn.query(query, &[&album_id])) { tracks.insert(row.get("id"), Track { ...
{ return Ok(None); }
conditional_block
albums.rs
use std::collections::HashMap; use postgres::GenericConnection as PostgresConnection; use db::pg::RowsExtension; use library::Result; const MAX_TOP_ALBUMS: i64 = 10; #[derive(RustcEncodable)] struct Track { name: String, is_favorite: bool, scrobbles: Vec<i32>, } #[derive(RustcEncodable)] pub struct Alb...
(conn: &PostgresConnection) -> Result<TopAlbums> { let query = r#" SELECT artists.name as artist, albums.name as album, albums.plays as plays FROM albums LEFT JOIN artists ON artists.id = albums.artist_id ORDER BY albums.plays DESC OFFSET 0...
load_top_albums
identifier_name
base_protocol.py
from struct import pack from google.protobuf.message import DecodeError from twisted.internet.protocol import Protocol from twisted.python import log from relayserver.utility import get_hex_dump class BaseProtocol(Protocol): def write_message(self, message): data = message.SerializeToString() mess...
log.msg("Parsing [%s] in (%d) bytes." % (type_.__name__, len(message_raw))) message = type_() try: message.ParseFromString(message_raw) except DecodeError: raise else: if message.IsInitialized() is False: raise Exception("Message pars...
identifier_body
base_protocol.py
from struct import pack from google.protobuf.message import DecodeError from twisted.internet.protocol import Protocol from twisted.python import log from relayserver.utility import get_hex_dump class
(Protocol): def write_message(self, message): data = message.SerializeToString() message_len = len(data) prefix = pack('>I', message_len) total_len = len(prefix) + message_len log.msg("Message type [%s] serialized into (%d) bytes and wrapped as " ...
BaseProtocol
identifier_name
base_protocol.py
from struct import pack from google.protobuf.message import DecodeError from twisted.internet.protocol import Protocol from twisted.python import log from relayserver.utility import get_hex_dump
total_len = len(prefix) + message_len log.msg("Message type [%s] serialized into (%d) bytes and wrapped as " "(%d) bytes." % (message.__class__.__name__, message_len, total_len)) self.transport.write(prefix) self.transport.write(data) ...
class BaseProtocol(Protocol): def write_message(self, message): data = message.SerializeToString() message_len = len(data) prefix = pack('>I', message_len)
random_line_split
base_protocol.py
from struct import pack from google.protobuf.message import DecodeError from twisted.internet.protocol import Protocol from twisted.python import log from relayserver.utility import get_hex_dump class BaseProtocol(Protocol): def write_message(self, message): data = message.SerializeToString() mess...
return message
raise Exception("Message parse with type [%s] resulted in " "uninitialized message." % (type_))
conditional_block
tasks.py
""" This file contains celery tasks related to course content gating. """ import logging from celery import shared_task from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user from edx_django_utils.monitoring import set_code_owner_attribute from opaque_keys.edx.keys import Cou...
(usage_key, block_structure): """ Finds subsection of a block by recursively iterating over its parents :param usage_key: key of the block :param block_structure: block structure :return: sequential block """ parents = block_structure.get_parents(usage_key) if parents: for parent...
_get_subsection_of_block
identifier_name
tasks.py
""" This file contains celery tasks related to course content gating. """ import logging from celery import shared_task from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user from edx_django_utils.monitoring import set_code_owner_attribute from opaque_keys.edx.keys import Cou...
def _get_subsection_of_block(usage_key, block_structure): """ Finds subsection of a block by recursively iterating over its parents :param usage_key: key of the block :param block_structure: block structure :return: sequential block """ parents = block_structure.get_parents(usage_key) ...
try: user = User.objects.get(id=user_id) course_structure = get_course_blocks(user, store.make_course_usage_key(course_key)) completed_block_usage_key = UsageKey.from_string(block_id).map_into_course(course.id) subsection_block = _get_subsection_of_block(c...
conditional_block
tasks.py
""" This file contains celery tasks related to course content gating. """ import logging from celery import shared_task from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user from edx_django_utils.monitoring import set_code_owner_attribute from opaque_keys.edx.keys import Cou...
""" Finds subsection of a block by recursively iterating over its parents :param usage_key: key of the block :param block_structure: block structure :return: sequential block """ parents = block_structure.get_parents(usage_key) if parents: for parent_block in parents: if ...
identifier_body
tasks.py
""" This file contains celery tasks related to course content gating. """ import logging from celery import shared_task from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user from edx_django_utils.monitoring import set_code_owner_attribute from opaque_keys.edx.keys import Cou...
if parents: for parent_block in parents: if parent_block.block_type == 'sequential': return parent_block else: return _get_subsection_of_block(parent_block, block_structure)
parents = block_structure.get_parents(usage_key)
random_line_split
FieldFilterComponent.tsx
import { WorkItemTypeField } from '../data/AnalyticsTypes'; import * as Q from 'q'; import * as React from 'react'; import * as FluxTypes from './FluxTypes'; import { Store } from "VSS/Flux/Store"; import { Picker } from './PickerComponent'; import { AllowedOperator, FieldFilterConfigurationState, FieldFilterRowDat...
}
{ return <div className="field-filter-header"> <span className="filter-field-label">Field</span> <span className="filter-operation-label">Operation</span> <span className="filter-value-label">Value</span> </div>; }
identifier_body
FieldFilterComponent.tsx
import { WorkItemTypeField } from '../data/AnalyticsTypes'; import * as Q from 'q'; import * as React from 'react'; import * as FluxTypes from './FluxTypes'; import { Store } from "VSS/Flux/Store"; import { Picker } from './PickerComponent'; import { AllowedOperator, FieldFilterConfigurationState, FieldFilterRowDat...
(): JSX.Element { /* Note - This example is operating with a Picker control to illustrate ability to select from a known list, which does not allow for manual editing. VSS Combo or Fabric ComboBox controls do support hybrid models. */ return <div className="field-filter"> <Pick...
render
identifier_name
FieldFilterComponent.tsx
import { WorkItemTypeField } from '../data/AnalyticsTypes'; import * as Q from 'q'; import * as React from 'react'; import * as FluxTypes from './FluxTypes'; import { Store } from "VSS/Flux/Store"; import { Picker } from './PickerComponent'; import { AllowedOperator, FieldFilterConfigurationState, FieldFilterRowDat...
<a className="remove-filter-row-button " onClick={()=>{this.props.removeRow();}}><span role="button" className="bowtie-icon bowtie-edit-delete"></span></a> </div>; } } /** Renders a header row for Field Filter */ export class FieldFilterHeaderComponent extends React.Component<{}, {}> { pub...
<Picker className="value-picker" itemValues={this.props.suggestedValues} getItemText={(value: string)=> {return value;}} getItemId={(value: string)=>{ return value;}} initialSelectionId={this.props.settings.value} onChange={(value:string)=>{th...
random_line_split
admin.auth.guard.spec.ts
import { AdminAuthGuard } from './admin.auth.guard'; export function main()
expect(new AdminAuthGuard(mockCapabilites, mockError, mockCurrentUser).canActivate()).toBe(true); expect(mockError.handle).not.toHaveBeenCalled(); }); it('returns false/unauthenticated when not logged in', () => { loggedIn = false; hasRoot = false; expect(new AdminA...
{ describe('Admin Auth Guard', () => { let mockCurrentUser: any; let mockError: any; let mockCapabilites: any; describe('canActivate()', () => { let loggedIn: boolean; let hasRoot: boolean; beforeEach(() => { mockCurrentUser = { loggedIn: () => loggedIn }; mockCapab...
identifier_body
admin.auth.guard.spec.ts
import { AdminAuthGuard } from './admin.auth.guard'; export function
() { describe('Admin Auth Guard', () => { let mockCurrentUser: any; let mockError: any; let mockCapabilites: any; describe('canActivate()', () => { let loggedIn: boolean; let hasRoot: boolean; beforeEach(() => { mockCurrentUser = { loggedIn: () => loggedIn }; mockCa...
main
identifier_name
admin.auth.guard.spec.ts
import { AdminAuthGuard } from './admin.auth.guard'; export function main() { describe('Admin Auth Guard', () => { let mockCurrentUser: any; let mockError: any; let mockCapabilites: any; describe('canActivate()', () => { let loggedIn: boolean; let hasRoot: boolean; beforeEach(() =...
it('returns true when logged in and has root', () => { loggedIn = true; hasRoot = true; expect(new AdminAuthGuard(mockCapabilites, mockError, mockCurrentUser).canActivate()).toBe(true); expect(mockError.handle).not.toHaveBeenCalled(); }); it('returns false/unauthenti...
mockError = { handle: jasmine.createSpy('handle') }; });
random_line_split
wanderingspirit.js
'use strict'; const assert = require('./../../assert'); const common = require('./../../common'); let battle; describe('Wandering Spirit', function () { afterEach(() => battle.destroy()); it(`should exchange abilities with an attacker that makes contact`, function () { battle = common.createBattle([[ {specie...
{species: 'Runerigus', ability: 'wanderingspirit', moves: ['bodypress']}, ]]); battle.makeChoices('auto', 'move bodypress dynamax'); assert(battle.p1.active[0].hasAbility('overgrow')); assert(battle.p2.active[0].hasAbility('wanderingspirit')); }); it(`should not swap with Wonder Guard`, function () { ba...
it(`should not activate while Dynamaxed`, function () { battle = common.createBattle([[ {species: 'Decidueye', ability: 'overgrow', moves: ['shadowsneak']}, ], [
random_line_split
pep8.py
# Copyright (c) 2012-2013 Paul Tagliamonte <paultag@debian.org> # Copyright (c) 2013 Leo Cavaille <leo@cavaille.net> # # 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, inc...
return ('pep8', out.strip())
raise Exception("pep8 is not installed")
conditional_block
pep8.py
# Copyright (c) 2012-2013 Paul Tagliamonte <paultag@debian.org> # Copyright (c) 2013 Leo Cavaille <leo@cavaille.net> # # 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, inc...
failed = ret != 0 for issue in parse_pep8(out.splitlines()): analysis.results.append(issue) return (analysis, out, failed, None, None) def version(): out, _, ret = run_command(['pep8', '--version']) if ret != 0: raise Exception("pep8 is not installed") return ...
def pep8(dsc, analysis): run_command(["dpkg-source", "-x", dsc, "source-pep8"]) with cd('source-pep8'): out, _, ret = run_command(['pep8', '.'])
random_line_split
pep8.py
# Copyright (c) 2012-2013 Paul Tagliamonte <paultag@debian.org> # Copyright (c) 2013 Leo Cavaille <leo@cavaille.net> # # 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, inc...
def version(): out, _, ret = run_command(['pep8', '--version']) if ret != 0: raise Exception("pep8 is not installed") return ('pep8', out.strip())
run_command(["dpkg-source", "-x", dsc, "source-pep8"]) with cd('source-pep8'): out, _, ret = run_command(['pep8', '.']) failed = ret != 0 for issue in parse_pep8(out.splitlines()): analysis.results.append(issue) return (analysis, out, failed, None, None)
identifier_body
pep8.py
# Copyright (c) 2012-2013 Paul Tagliamonte <paultag@debian.org> # Copyright (c) 2013 Leo Cavaille <leo@cavaille.net> # # 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, inc...
(): out, _, ret = run_command(['pep8', '--version']) if ret != 0: raise Exception("pep8 is not installed") return ('pep8', out.strip())
version
identifier_name
yahoo-request.js
var HttpRequestStack = require('../lib/http-stack').HttpRequestStack; // Create the 'low-level' net.Stream we're going to be 'stacking' on var conn = require('net').createConnection(80, 'www.yahoo.com'); conn.on('connect', function() { console.log('connected!'); // Create our first "stack", the HttpRequestStac...
]); //req.end(); // 'response' is fired after the final HTTP header has been parsed. 'res' // is a ReadStream, that also contains 'rawHeaders', 'headers' properties. req.on('response', function(res) { res.pipe(process.stdout); res.on('data', function(chunk) { //console.error(chunk.toStrin...
req.get("/", [ "Host: www.yahoo.com" //"Connection: close", //"Accept-Encoding: gzip"
random_line_split
list_cases.py
50 else _MAX_OFFSET _caseGroupNumbers = None # for displaying cases owned by an associate as per SFDC _associateSSOName = None _view = None @classmethod def get_usage(cls): ''' The usage statement that will be printed by OptionParser. Example: - %prog -c CA...
random_line_split
list_cases.py
_MAX_OFFSET else int(_MAX_OFFSET) _limit = 50 if _MAX_OFFSET >= 50 else _MAX_OFFSET _caseGroupNumbers = None # for displaying cases owned by an associate as per SFDC _associateSSOName = None _view = None @classmethod def get_usage(cls): ''' The usage statement that will be...
(self): if self._options['casegroup']: valid_groups = [] given_groupAry = str(self._options['casegroup']).split(',') real_groupAry = common.get_groups() for i in given_groupAry: match = False for j in real_groupAry: ...
_check_case_group
identifier_name
list_cases.py
_MAX_OFFSET else int(_MAX_OFFSET) _limit = 50 if _MAX_OFFSET >= 50 else _MAX_OFFSET _caseGroupNumbers = None # for displaying cases owned by an associate as per SFDC _associateSSOName = None _view = None @classmethod def get_usage(cls): ''' The usage statement that will be...
except RequestError, re: if re.status == 404: msg = _("Unable to find user %s" % username) else: msg = _('Problem querying the support services API. Reason: ' '%s' % re.reason) print msg logger.log(logging...
if not (str(self._options['owner']).lower() == 'all' or self._caseGroupNumbers or self._options['ungrouped']): # this will trigger the display of cases owned as per SFDC self._associateSSOName = username self._vi...
conditional_block
list_cases.py
_MAX_OFFSET else int(_MAX_OFFSET) _limit = 50 if _MAX_OFFSET >= 50 else _MAX_OFFSET _caseGroupNumbers = None # for displaying cases owned by an associate as per SFDC _associateSSOName = None _view = None @classmethod def get_usage(cls): ''' The usage statement that will be...
def get_more_options(self, num_options): if (len(self.casesAry) < self._nextOffset or len(self.casesAry) == 0 or self._nextOffset > self._MAX_OFFSET): # Either we did not max out on results last time, there were # no results last time, or we have seen more t...
return self._submenu_opts
identifier_body
VoiceRecordComposerTile.tsx
governing permissions and limitations under the License. */ import React, { ReactNode } from "react"; import { Room } from "matrix-js-sdk/src/models/room"; import { MsgType } from "matrix-js-sdk/src/@types/event"; import { logger } from "matrix-js-sdk/src/logger"; import { Optional } from "matrix-events-sdk"; import...
() { await VoiceRecordingStore.instance.disposeRecording(this.props.room.roomId); // Reset back to no recording, which means no phase (ie: restart component entirely) this.setState({ recorder: null, recordingPhase: null, didUploadFail: false }); } private onCancel = async () => { ...
disposeRecording
identifier_name
VoiceRecordComposerTile.tsx
governing permissions and limitations under the License. */ import React, { ReactNode } from "react"; import { Room } from "matrix-js-sdk/src/models/room"; import { MsgType } from "matrix-js-sdk/src/@types/event"; import { logger } from "matrix-js-sdk/src/logger"; import { Optional } from "matrix-events-sdk"; import...
private onCancel = async () => { await this.disposeRecording(); }; public onRecordStartEndClick = async () => { if (this.state.recorder) { await this.state.recorder.stop(); return; } // The "microphone access error" dialogs are used a lot, so let's...
{ await VoiceRecordingStore.instance.disposeRecording(this.props.room.roomId); // Reset back to no recording, which means no phase (ie: restart component entirely) this.setState({ recorder: null, recordingPhase: null, didUploadFail: false }); }
identifier_body
VoiceRecordComposerTile.tsx
from "../elements/InlineSpinner"; import { PlaybackManager } from "../../../audio/PlaybackManager"; interface IProps { room: Room; } interface IState { recorder?: VoiceRecording; recordingPhase?: RecordingState; didUploadFail?: boolean; } /** * Container tile for rendering the voice message recorde...
}
random_line_split
VoiceRecordComposerTile.tsx
governing permissions and limitations under the License. */ import React, { ReactNode } from "react"; import { Room } from "matrix-js-sdk/src/models/room"; import { MsgType } from "matrix-js-sdk/src/@types/event"; import { logger } from "matrix-js-sdk/src/logger"; import { Optional } from "matrix-events-sdk"; import...
// only other UI is the recording-in-progress UI return <div className="mx_MediaBody mx_VoiceMessagePrimaryContainer mx_VoiceRecordComposerTile_recording"> <LiveRecordingClock recorder={this.state.recorder} /> <LiveRecordingWaveform recorder={this.state.recorder} /> </d...
{ return <RecordingPlayback playback={this.state.recorder.getPlayback()} />; }
conditional_block
index.ts
import AssertAgainstNamedBlocks from './assert-against-named-blocks'; import AssertIfHelperWithoutArguments from './assert-if-helper-without-arguments';
import TransformActionSyntax from './transform-action-syntax'; import TransformAttrsIntoArgs from './transform-attrs-into-args'; import TransformComponentInvocation from './transform-component-invocation'; import TransformEachInIntoEach from './transform-each-in-into-each'; import TransformEachTrackArray from './transf...
import AssertInputHelperWithoutBlock from './assert-input-helper-without-block'; import AssertLocalVariableShadowingHelperInvocation from './assert-local-variable-shadowing-helper-invocation'; import AssertReservedNamedArguments from './assert-reserved-named-arguments'; import AssertSplattributeExpressions from './asse...
random_line_split
index.ts
import AssertAgainstNamedBlocks from './assert-against-named-blocks'; import AssertIfHelperWithoutArguments from './assert-if-helper-without-arguments'; import AssertInputHelperWithoutBlock from './assert-input-helper-without-block'; import AssertLocalVariableShadowingHelperInvocation from './assert-local-variable-shad...
if (!EMBER_NAMED_BLOCKS) { transforms.push(AssertAgainstNamedBlocks); } export default Object.freeze(transforms);
{ transforms.push(DeprecateSendAction); }
conditional_block