file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
router_module.ts | /**
* @license
* Copyright Google LLC 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
*/
import {APP_BASE_HREF, HashLocationStrategy, Location, LOCATION_INITIALIZED, LocationStrategy, PathLocationStrategy, ... | : RouterInitializer) {
return r.appInitializer.bind(r);
}
export function getBootstrapListener(r: RouterInitializer) {
return r.bootstrapListener.bind(r);
}
/**
* A [DI token](guide/glossary/#di-token) for the router initializer that
* is called after the app is bootstrapped.
*
* @publicApi
*/
export const R... | tAppInitializer(r | identifier_name |
router_module.ts | /**
* @license
* Copyright Google LLC 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
*/
import {APP_BASE_HREF, HashLocationStrategy, Location, LOCATION_INITIALIZED, LocationStrategy, PathLocationStrategy, ... | private destroyed = false;
private resultOfPreactivationDone = new Subject<void>();
constructor(private injector: Injector) {}
appInitializer(): Promise<any> {
const p: Promise<any> = this.injector.get(LOCATION_INITIALIZED, Promise.resolve(null));
return p.then(() => {
// If the injector was des... | * 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 | /**
* @license
* Copyright Google LLC 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
*/
import {APP_BASE_HREF, HashLocationStrategy, Location, LOCATION_INITIALIZED, LocationStrategy, PathLocationStrategy, ... | /**
* A [DI token](guide/glossary/#di-token) for the router initializer that
* is called after the app is bootstrapped.
*
* @publicApi
*/
export const ROUTER_INITIALIZER =
new InjectionToken<(compRef: ComponentRef<any>) => void>('Router Initializer');
export function provideRouterInitializer(): ReadonlyArray<... | return r.bootstrapListener.bind(r);
}
| identifier_body |
router_module.ts | /**
* @license
* Copyright Google LLC 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
*/
import {APP_BASE_HREF, HashLocationStrategy, Location, LOCATION_INITIALIZED, LocationStrategy, PathLocationStrategy, ... | if (opts.paramsInheritanceStrategy) {
router.paramsInheritanceStrategy = opts.paramsInheritanceStrategy;
}
if (opts.relativeLinkResolution) {
router.relativeLinkResolution = opts.relativeLinkResolution;
}
if (opts.urlUpdateStrategy) {
router.urlUpdateStrategy = opts.urlUpdateStrategy;
}
if ... | 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... | ;
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)
);
(case ins... | {
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 | /**
* @fileoverview Driver script for speech processing.
* @author aravart@cs.wisc.edu (Ara Vartanian), dliang@cs.wisc.edu (David Liang)
*/
goog.provide('SpeechGames');
goog.provide('SpeechGames.Speech');
goog.require('Blockly.Workspace');
goog.require('SpeechBlocks.Controller');
goog.require('SpeechBlocks.Interpre... |
if (SpeechGames.getParameterByName_('microphone')) {
SpeechGames.speech.setMicInterval_();
}
if (SpeechGames.getParameterByName_('debug')) {
$('#q').css('visibility','visible');
} else {
$('#debug').hide();
}
// listen for mouse clicks, key presses
$('#q')
.change(SpeechGames.speech.sch... | 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 | //! 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
//! channel, provided that connection does not create a cycle.
//!
//! A graph is initialized by adding each d... |
).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 | //! 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
//! channel, provided that connection does not create a cycle.
//!
//! A graph is initialized by adding each d... | () {
let mock1 = MockAudioDevice::new("mock1", 1, 1);
let mock2 = MockAudioDevice::new("mock2", 1, 1);
let mut graph = DeviceGraph::new();
let mock1 = graph.add_node(mock1);
let mock2 = graph.add_node(mock2);
graph.add_edge(mock1, 0, mock2, 0).unwrap();
graph.add... | test_direct_cycle | identifier_name |
bwt.rs | use sa::{insert, suffix_array};
use std::ops::Index;
/// Generate the [Burrows-Wheeler Transform](https://en.wikipedia.org/wiki/Burrows%E2%80%93Wheeler_transform)
/// of the given input.
///
/// ``` rust
/// let text = String::from("The quick brown fox jumps over the lazy dog");
/// let bw = nucleic_acid::bwt(text.as... |
/// Get the nearest position of a character in the internal BWT data.
///
/// The `count` and `search` methods rely on this method for finding occurrences.
/// For example, we can do soemthing like this,
///
/// ``` rust
/// use nucleic_acid::FMIndex;
/// let fm = FMIndex::new(b"Hello,... | {
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 sa::{insert, suffix_array};
use std::ops::Index;
/// Generate the [Burrows-Wheeler Transform](https://en.wikipedia.org/wiki/Burrows%E2%80%93Wheeler_transform)
/// of the given input.
///
/// ``` rust
/// let text = String::from("The quick brown fox jumps over the lazy dog");
/// let bw = nucleic_acid::bwt(text.as... | } | random_line_split | |
bwt.rs | use sa::{insert, suffix_array};
use std::ops::Index;
/// Generate the [Burrows-Wheeler Transform](https://en.wikipedia.org/wiki/Burrows%E2%80%93Wheeler_transform)
/// of the given input.
///
/// ``` rust
/// let text = String::from("The quick brown fox jumps over the lazy dog");
/// let bw = nucleic_acid::bwt(text.as... | (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) | ;
| {
"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 | import collections
import ctypes
import hashlib
import os
import platform
import random
import re
import string
import sys
import traceback
from couchpotato.core.helpers.encoding import simplifyString, toSafeString, ss, sp
from couchpotato.core.logger import CPLog
import six
from six.moves import map, zip, filter
lo... | 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 | import collections
import ctypes
import hashlib
import os
import platform
import random
import re
import string
import sys
import traceback
from couchpotato.core.helpers.encoding import simplifyString, toSafeString, ss, sp
from couchpotato.core.logger import CPLog
import six
from six.moves import map, zip, filter
lo... | (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 | import collections
import ctypes
import hashlib
import os
import platform
import random
import re
import string
import sys
import traceback
from couchpotato.core.helpers.encoding import simplifyString, toSafeString, ss, sp
from couchpotato.core.logger import CPLog
import six
from six.moves import map, zip, filter
lo... |
elif os.path.isfile(path):
total_size += os.path.getsize(path)
return total_size / 1048576 # MB
def find(func, iterable):
for item in iterable:
if func(item):
return item
return None
def compareVersions(version1, version2):
def normalize(v):
return... | total_size += os.path.getsize(sp(os.path.join(dirpath, f))) | conditional_block |
variable.py | import collections
import ctypes
import hashlib
import os
import platform
import random
import re
import string
import sys
import traceback
from couchpotato.core.helpers.encoding import simplifyString, toSafeString, ss, sp
from couchpotato.core.logger import CPLog
import six
from six.moves import map, zip, filter
lo... |
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 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/... |
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 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/... |
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 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/... | ():
"""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 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/... |
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() | ;
| {
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 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2012 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... | searchopts = {'count': self._limit, 'start': 0}
self.casesAry = self._get_cases(searchopts)
self._nextOffset = self._limit
if not self._parse_cases(self.casesAry):
msg = _("Unable to find cases")
print msg
logger.log(logging.WARNING, msg)
... | random_line_split | |
list_cases.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2012 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... | (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 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2012 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... |
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 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2012 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... |
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 | /*
Copyright 2021 - 2022 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed... | () {
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 | /*
Copyright 2021 - 2022 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed... |
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 | /*
Copyright 2021 - 2022 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed... | } | } | random_line_split |
VoiceRecordComposerTile.tsx | /*
Copyright 2021 - 2022 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed... |
// 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.