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
CorsCheck.js
import React, {useState, useEffect} from 'react' import {Text, Container, Flex, Spinner, Stack} from '@sanity/ui' import {versionedClient} from './versionedClient' const checkCors = () => Promise.all([ versionedClient.request({uri: '/ping', withCredentials: false}).then(() => true), versionedClient .re...
export default function CorsCheck() { const [state, setState] = useState({isLoading: true}) useEffect(() => { checkCors().then((res) => setState({ result: res, isLoading: false, }) ) }, []) const {isLoading, result} = state const origin = window.location.origin || ...
{ const response = result && result.error && result.error.response const message = response && response.body && response.body.message if (!message) { return <>{children}</> } return ( <div> <Text>Error message:</Text> <pre> <code>{response.body.message}</code> </pre> {...
identifier_body
day20.rs
extern crate clap; extern crate regex; use clap::App; fn main() { let matches = App::new("day20") .version("v1.0") .author("Andrew Rink <andrewrink@gmail.com>") .args_from_usage("<NUM> 'Minimum present number'") .get_matches(); let num = matches.value_of("NUM").unwrap().parse:...
for (i, e) in v.iter().enumerate() { if *e >= presents { println!("Part 1: House {} received {} presents", i+1, e); break; } } }
} }
random_line_split
day20.rs
extern crate clap; extern crate regex; use clap::App; fn main() { let matches = App::new("day20") .version("v1.0") .author("Andrew Rink <andrewrink@gmail.com>") .args_from_usage("<NUM> 'Minimum present number'") .get_matches(); let num = matches.value_of("NUM").unwrap().parse:...
fn find_house_number(presents : usize) { let target = presents / 10; let mut v = vec![0; target]; for i in 1..target+1 { let mut j = i; while j <= target { let entry = v.get_mut(j-1).unwrap(); *entry += i*10; j += i; } } for (i, e) ...
{ let sz = presents/10; let mut v = vec![0; sz]; for i in 1..sz+1 { let mut j = i; let mut cnt = 0; while j <= sz && cnt < 50 { let entry = v.get_mut(j-1).unwrap(); *entry += i*11; j += i; cnt += 1; } } for (i, e) ...
identifier_body
day20.rs
extern crate clap; extern crate regex; use clap::App; fn main() { let matches = App::new("day20") .version("v1.0") .author("Andrew Rink <andrewrink@gmail.com>") .args_from_usage("<NUM> 'Minimum present number'") .get_matches(); let num = matches.value_of("NUM").unwrap().parse:...
(presents : usize) { let sz = presents/10; let mut v = vec![0; sz]; for i in 1..sz+1 { let mut j = i; let mut cnt = 0; while j <= sz && cnt < 50 { let entry = v.get_mut(j-1).unwrap(); *entry += i*11; j += i; cnt += 1; } ...
find_house_number_part2
identifier_name
day20.rs
extern crate clap; extern crate regex; use clap::App; fn main() { let matches = App::new("day20") .version("v1.0") .author("Andrew Rink <andrewrink@gmail.com>") .args_from_usage("<NUM> 'Minimum present number'") .get_matches(); let num = matches.value_of("NUM").unwrap().parse:...
} } fn find_house_number(presents : usize) { let target = presents / 10; let mut v = vec![0; target]; for i in 1..target+1 { let mut j = i; while j <= target { let entry = v.get_mut(j-1).unwrap(); *entry += i*10; j += i; } } for...
{ println!("Part 2: House {} received {} presents", i+1, e); break; }
conditional_block
server_usage.py
# Copyright 2013 OpenStack Foundation # # 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 a...
class Server_usage(extensions.ExtensionDescriptor): """Adds launched_at and terminated_at on Servers.""" name = "ServerUsage" alias = "OS-SRV-USG" namespace = ("http://docs.openstack.org/compute/ext/" "server_usage/api/v1.1") updated = "2013-04-29T00:00:00Z" def get_control...
def __init__(self, *args, **kwargs): super(ServerUsageController, self).__init__(*args, **kwargs) self.compute_api = compute.API() def _extend_server(self, server, instance): for k in ['launched_at', 'terminated_at']: key = "%s:%s" % (Server_usage.alias, k) # NOTE(da...
identifier_body
server_usage.py
# Copyright 2013 OpenStack Foundation # # 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 a...
@wsgi.extends def detail(self, req, resp_obj): context = req.environ['nova.context'] if authorize(context): # Attach our slave template to the response object resp_obj.attach(xml=ServerUsagesTemplate()) servers = list(resp_obj.obj['servers']) for...
resp_obj.attach(xml=ServerUsageTemplate()) server = resp_obj.obj['server'] db_instance = req.get_db_instance(server['id']) # server['id'] is guaranteed to be in the cache due to # the core API adding it in its 'show' method. self._extend_server(server, db_inst...
conditional_block
server_usage.py
# Copyright 2013 OpenStack Foundation # # 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 a...
self.compute_api = compute.API() def _extend_server(self, server, instance): for k in ['launched_at', 'terminated_at']: key = "%s:%s" % (Server_usage.alias, k) # NOTE(danms): Historically, this timestamp has been generated # merely by grabbing str(datetime) of a ...
class ServerUsageController(wsgi.Controller): def __init__(self, *args, **kwargs): super(ServerUsageController, self).__init__(*args, **kwargs)
random_line_split
server_usage.py
# Copyright 2013 OpenStack Foundation # # 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 a...
(elem): elem.set('{%s}launched_at' % Server_usage.namespace, '%s:launched_at' % Server_usage.alias) elem.set('{%s}terminated_at' % Server_usage.namespace, '%s:terminated_at' % Server_usage.alias) class ServerUsageTemplate(xmlutil.TemplateBuilder): def construct(self): roo...
make_server
identifier_name
functions_66.js
var searchData= [ ['file',['File',['../classsol_1_1_file.html#adadcbaa4e64c50bf4416b77318c90b1f',1,'sol::File::File(const std::string &amp;filename, const std::string &amp;mode)'],['../classsol_1_1_file.html#a6ec6975155acae9a784ee39252ccd974',1,'sol::File::File()=default']]], ['fillbuffer',['fillBuffer',['../classs...
['framebuffer',['Framebuffer',['../classsol_1_1_framebuffer.html#a494d491b79efe568626b025624595da6',1,'sol::Framebuffer']]] ];
random_line_split
Matrix.page.ts
import { element, by, $, $$, ElementFinder, ElementArrayFinder, browser, ExpectedConditions as EC } from 'protractor'; import { FamilyImage } from './Components'; import { AbstractPage } from './Abstract.page'; export class MatrixPage { static url = `${AbstractPage.url}/matrix`; static filterByThing: ElementFind...
static getShareButtonInHamburgerMenu(social: string): ElementFinder { return $(`main-menu div[class*="share-button ${social}"]`); } static async waitForSpinner(): Promise<{}> { return browser.wait(EC.invisibilityOf(this.spinner), 10000); } static async getFamilyIncome(index: number): Promise<numbe...
{ return element(by.id(`${type}-filter`)); }
identifier_body
Matrix.page.ts
import { element, by, $, $$, ElementFinder, ElementArrayFinder, browser, ExpectedConditions as EC } from 'protractor'; import { FamilyImage } from './Components'; import { AbstractPage } from './Abstract.page'; export class MatrixPage { static url = `${AbstractPage.url}/matrix`; static filterByThing: ElementFind...
(): Promise<{}> { return browser.wait(EC.invisibilityOf(this.spinner), 10000); } static async getFamilyIncome(index: number): Promise<number> { return this.familyIncomeOnImage .get(index) .getText() .then(income => Number(income.replace(/\D/g, ''))); } static async getFamilyIncomeFro...
waitForSpinner
identifier_name
Matrix.page.ts
import { element, by, $, $$, ElementFinder, ElementArrayFinder, browser, ExpectedConditions as EC } from 'protractor'; import { FamilyImage } from './Components'; import { AbstractPage } from './Abstract.page'; export class MatrixPage { static url = `${AbstractPage.url}/matrix`; static filterByThing: ElementFind...
} static getShareButtonInHamburgerMenu(social: string): ElementFinder { return $(`main-menu div[class*="share-button ${social}"]`); } static async waitForSpinner(): Promise<{}> { return browser.wait(EC.invisibilityOf(this.spinner), 10000); } static async getFamilyIncome(index: number): Promise<nu...
static getFilter(type: string): ElementFinder { return element(by.id(`${type}-filter`));
random_line_split
parser.rs
/* Copyright (C) 2018 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARR...
(input: &str) -> Result<u32, std::num::ParseIntError> { input.parse::<u32>() } named!(pub parse_message<String>, do_parse!( len: map_res!( map_res!(take_until!(":"), std::str::from_utf8), parse_len) >> _sep: take!(1) >> msg: take_str!(len) >> ...
parse_len
identifier_name
parser.rs
/* Copyright (C) 2018 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARR...
}
{ let buf = b"12:Hello World!4:Bye."; let result = parse_message(buf); match result { Ok((remainder, message)) => { // Check the first message. assert_eq!(message, "Hello World!"); // And we should have 6 bytes left. a...
identifier_body
parser.rs
/* Copyright (C) 2018 Open Information Security Foundation *
* the GNU General Public License version 2 as published by the Free * Software Foundation. * * 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 Public Lice...
* You can copy, redistribute or modify this Program under the terms of
random_line_split
mtphelper.js
"use strict"; // // Copyright (c) 2017 Ricoh Company, Ltd. All Rights Reserved. // See LICENSE for more information. // //console.log(exports, require, module, __filename, __dirname, process, global); const MTPDevice = function(deviceId) { this.deviceId = deviceId; } const MTPHelper = { version: "1.0.0", help...
MTPHelper.child.readlineIn.on('line', MTPHelper.stdout_proc); MTPHelper.child.readlineErr = readline.createInterface(MTPHelper.child.stderr, {}); MTPHelper.child.readlineErr.on('line', MTPHelper.stderr_proc); child.execFile(MTPHelper.executable, ["-v"], (err, sout, serr)=>{ ...
console.log("mtphelper: spawn '" + MTPHelper.executable + "'"); const child = require('child_process'); const readline = require('readline'); MTPHelper.child = child.execFile(MTPHelper.executable); MTPHelper.child.readlineIn = readline.createInterface(MTPHelper.child.s...
random_line_split
mtphelper.js
"use strict"; // // Copyright (c) 2017 Ricoh Company, Ltd. All Rights Reserved. // See LICENSE for more information. // //console.log(exports, require, module, __filename, __dirname, process, global); const MTPDevice = function(deviceId) { this.deviceId = deviceId; } const MTPHelper = { version: "1.0.0", help...
return new Promise((resolve2, reject2)=>{ var dev = new MTPDevice(did); dev.deviceInfo().then((info)=>{ result[did] = info; resolve2(); }); }); })).then(()=>{ resolve(result); }); }).catch((e)=>{ ...
{ return undefined; }
conditional_block
core.client.lodash.js
(function() { 'use strict'; angular .module('core') .run(run); run.$inject = ['$rootScope']; /* @ngInject */ function run($rootScope)
})();
{ var _ = $rootScope, methods = {}; methods.chunk = function(array, n) { return _.transform(array, function(result, el, i, arr) { return i % n === 0 ? result.push(arr.slice(i, i + n)) : null; }); }; methods.stripBase64 = function(str) { return str.replace(/^data:image\/...
identifier_body
core.client.lodash.js
(function() { 'use strict'; angular .module('core') .run(run);
run.$inject = ['$rootScope']; /* @ngInject */ function run($rootScope) { var _ = $rootScope, methods = {}; methods.chunk = function(array, n) { return _.transform(array, function(result, el, i, arr) { return i % n === 0 ? result.push(arr.slice(i, i + n)) : null; }); }; ...
random_line_split
core.client.lodash.js
(function() { 'use strict'; angular .module('core') .run(run); run.$inject = ['$rootScope']; /* @ngInject */ function
($rootScope) { var _ = $rootScope, methods = {}; methods.chunk = function(array, n) { return _.transform(array, function(result, el, i, arr) { return i % n === 0 ? result.push(arr.slice(i, i + n)) : null; }); }; methods.stripBase64 = function(str) { return str.replace(/...
run
identifier_name
proxyhandler.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Utilities for the implementation of JSAPI proxy handlers. #![deny(missing_docs)] use dom::bindings::conversi...
} /// No-op required hook. pub unsafe extern fn enumerate(_cx: *mut JSContext, _obj: *mut JSObject, _v: *mut AutoIdVector) -> bool { true }
random_line_split
proxyhandler.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Utilities for the implementation of JSAPI proxy handlers. #![deny(missing_docs)] use dom::bindings::conversi...
(cx: *mut JSContext, proxy: *mut JSObject, id: jsid, bp: *mut bool) -> bool { let expando = get_expando_object(proxy); if expando.is_null() { *bp = true; return true; } return delete_property_by_id(cx, expando, id, &mut *bp); } /// Returns the stringificatio...
delete
identifier_name
proxyhandler.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Utilities for the implementation of JSAPI proxy handlers. #![deny(missing_docs)] use dom::bindings::conversi...
/// Set the property descriptor's object to `obj` and set it to enumerable, /// and writable if `readonly` is true. pub fn fill_property_descriptor(desc: &mut JSPropertyDescriptor, obj: *mut JSObject, readonly: bool) { desc.obj = obj; desc.attrs = if readonly { JSPROP_READONLY ...
{ unsafe { assert!(is_dom_proxy(obj)); let mut expando = get_expando_object(obj); if expando.is_null() { expando = JS_NewObjectWithGivenProto(cx, ptr::null_mut(), ptr::null_mut(), Ge...
identifier_body
proxyhandler.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Utilities for the implementation of JSAPI proxy handlers. #![deny(missing_docs)] use dom::bindings::conversi...
else { 0 } | JSPROP_ENUMERATE; desc.getter = None; desc.setter = None; desc.shortid = 0; } /// No-op required hook. pub unsafe extern fn get_own_property_names(_cx: *mut JSContext, _obj: *mut JSObject, _v: *mut AutoIdV...
{ JSPROP_READONLY }
conditional_block
console.py
"""a readline console module (unix only). maxime.tournier@brain.riken.jp the module starts a subprocess for the readline console and communicates through pipes (prompt/cmd). the console is polled through a timer, which depends on PySide. """ from select import select import os import sys import signal if __name_...
_cleanup = c class Console(code.InteractiveConsole): def __init__(self, locals = None, timeout = 100): """ python interpreter taking input from console subprocess scope is provided through 'locals' (usually: locals() or globals()) 't...
_cleanup()
conditional_block
console.py
"""a readline console module (unix only). maxime.tournier@brain.riken.jp the module starts a subprocess for the readline console and communicates through pipes (prompt/cmd). the console is polled through a timer, which depends on PySide. """ from select import select import os import sys import signal if __name_...
def __exit__(self, type, value, traceback): readline.write_history_file( self.filename ) def cleanup(*args): print('console cleanup') os.system('stty sane') for sig in [signal.SIGQUIT, signal.SIGTERM, signal.SIGILL, signal.SI...
# print 'loaded console history from', self.filename except IOError: pass return self
random_line_split
console.py
"""a readline console module (unix only). maxime.tournier@brain.riken.jp the module starts a subprocess for the readline console and communicates through pipes (prompt/cmd). the console is polled through a timer, which depends on PySide. """ from select import select import os import sys import signal if __name_...
def recv(): while True: res = file_in.readline().rstrip('\n') read, _, _ = select([ file_in ], [], [], 0) if not read: return res class History: """readline history safe open/close""" def __init__(self, filename): s...
file_out.write(data + '\n') file_out.flush()
identifier_body
console.py
"""a readline console module (unix only). maxime.tournier@brain.riken.jp the module starts a subprocess for the readline console and communicates through pipes (prompt/cmd). the console is polled through a timer, which depends on PySide. """ from select import select import os import sys import signal if __name_...
(code.InteractiveConsole): def __init__(self, locals = None, timeout = 100): """ python interpreter taking input from console subprocess scope is provided through 'locals' (usually: locals() or globals()) 'timeout' (in milliseconds) sets how often i...
Console
identifier_name
sign.rs
// Copyright 2017-2021 int08h 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 // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to...
} impl Signer { pub fn new() -> Self { let rng = rand::SystemRandom::new(); let mut seed = [0u8; 32]; rng.fill(&mut seed).unwrap(); Signer::from_seed(&seed) } pub fn from_seed(seed: &[u8]) -> Self { Signer { key_pair: Ed25519KeyPair::from_seed_unchecke...
{ Self::new() }
identifier_body
sign.rs
// Copyright 2017-2021 int08h 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 // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to...
let pubkey = hex::decode( "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a", ).unwrap(); let signature = hex::decode( "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b" ...
mod test { use super::*; #[test] fn verify_ed25519_sig_on_empty_message() {
random_line_split
sign.rs
// Copyright 2017-2021 int08h 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 // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to...
() { let seed = hex::decode("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60") .unwrap(); let expected_sig = hex::decode( "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b" )...
sign_ed25519_empty_message
identifier_name
cookie_storage.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Implementation of cookie storage as specified in //! http://tools.ietf.org/html/rfc6265 use net_traits::Cooki...
// http://tools.ietf.org/html/rfc6265#section-5.3 pub fn remove(&mut self, cookie: &Cookie, source: CookieSource) -> Result<Option<Cookie>, ()> { // Step 1 let position = self.cookies.iter().position(|c| { c.cookie.domain == cookie.cookie.domain && c.cookie.path == cookie...
random_line_split
cookie_storage.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Implementation of cookie storage as specified in //! http://tools.ietf.org/html/rfc6265 use net_traits::Cooki...
(&mut self, url: &Url, source: CookieSource) -> Option<String> { let filterer = |c: &&mut Cookie| -> bool { info!(" === SENT COOKIE : {} {} {:?} {:?}", c.cookie.name, c.cookie.value, c.cookie.domain, c.cookie.path); info!(" === SENT COOKIE RESULT {}", c.appropriate_for_...
cookies_for_url
identifier_name
cookie_storage.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Implementation of cookie storage as specified in //! http://tools.ietf.org/html/rfc6265 use net_traits::Cooki...
// Step 11 if let Some(old_cookie) = old_cookie.unwrap() { // Step 11.3 cookie.creation_time = old_cookie.creation_time; } // Step 12 self.cookies.push(cookie); } pub fn cookie_comparator(a: &Cookie, b: &Cookie) -> Ordering { let a_path...
{ return; }
conditional_block
cookie_storage.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Implementation of cookie storage as specified in //! http://tools.ietf.org/html/rfc6265 use net_traits::Cooki...
// http://tools.ietf.org/html/rfc6265#section-5.3 pub fn push(&mut self, mut cookie: Cookie, source: CookieSource) { let old_cookie = self.remove(&cookie, source); if old_cookie.is_err() { // This new cookie is not allowed to overwrite an existing one. return; }...
{ // Step 1 let position = self.cookies.iter().position(|c| { c.cookie.domain == cookie.cookie.domain && c.cookie.path == cookie.cookie.path && c.cookie.name == cookie.cookie.name }); if let Some(ind) = position { let c = self.cookies.remo...
identifier_body
surface.rs
use {Scalar, TOLERANCE}; use maths::{CrossProduct, DotProduct, UnitVec3D, Vec3D}; /// Represents a `Surface` for a given set of points. #[derive(Copy, Clone)] pub struct Surface { /// The `Surface` normal pub normal: UnitVec3D, /// The node indices associated with the `Surface` pub nodes: [usize; 3], }...
return Surface { normal: normal, nodes: [index_0, index_1, index_2], }; } /// Computes the centroid of a `Surface` using the node indices in the /// `Surface` and the point cloud provided. pub fn compute_centroid(surface: &Surface, vertices: &Vec<Vec3D>) -> Vec...
{ normal = -normal; }
conditional_block
surface.rs
use {Scalar, TOLERANCE}; use maths::{CrossProduct, DotProduct, UnitVec3D, Vec3D}; /// Represents a `Surface` for a given set of points. #[derive(Copy, Clone)] pub struct Surface { /// The `Surface` normal pub normal: UnitVec3D, /// The node indices associated with the `Surface` pub nodes: [usize; 3], }...
(surface: &Surface, vertices: &Vec<Vec3D>) -> Vec3D { return surface.nodes.iter() .fold(Vec3D::zero(), |total, &index| { total + vertices[index] }) / 3.0; } }
compute_centroid
identifier_name
surface.rs
use {Scalar, TOLERANCE};
/// Represents a `Surface` for a given set of points. #[derive(Copy, Clone)] pub struct Surface { /// The `Surface` normal pub normal: UnitVec3D, /// The node indices associated with the `Surface` pub nodes: [usize; 3], } impl Surface { /// Creates a new `Surface` from the point cloud and indices p...
use maths::{CrossProduct, DotProduct, UnitVec3D, Vec3D};
random_line_split
issue-21384.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<T : Clone>(arg: T) -> T { arg.clone() } #[derive(PartialEq)] struct Test(int); fn main() { // Check that ranges implement clone assert!(test(1..5) == (1..5)); assert!(test(..5) == (..5)); assert!(test(1..) == (1..)); assert!(test(FullRange) == (FullRange)); // Check that ranges can still...
test
identifier_name
issue-21384.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} #[derive(PartialEq)] struct Test(int); fn main() { // Check that ranges implement clone assert!(test(1..5) == (1..5)); assert!(test(..5) == (..5)); assert!(test(1..) == (1..)); assert!(test(FullRange) == (FullRange)); // Check that ranges can still be used with non-clone limits assert!(...
// option. This file may not be copied, modified, or distributed // except according to those terms. fn test<T : Clone>(arg: T) -> T { arg.clone()
random_line_split
issue-21384.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ // Check that ranges implement clone assert!(test(1..5) == (1..5)); assert!(test(..5) == (..5)); assert!(test(1..) == (1..)); assert!(test(FullRange) == (FullRange)); // Check that ranges can still be used with non-clone limits assert!((Test(1)..Test(5)) == (Test(1)..Test(5))); }
identifier_body
gd.js
tinymce.addI18n('gd',{ "Cut": "Gearr \u00e0s", "Heading 5": "Ceann-sgr\u00ecobhadh 5", "Header 2": "Bann-cinn 2", "Your browser doesn't support direct access to the clipboard. Please use the Ctrl+X\/C\/V keyboard shortcuts instead.": "Chan eil am brabhsair agad a' cur taic ri inntrigeadh d\u00ecreach dhan st\u00f2r-bh\...
"Footer": "Bann-coise", "Delete row": "Sguab \u00e0s an r\u00e0gh", "Paste row before": "Cuir ann r\u00e0gh roimhe", "Scope": "Sg\u00f2p", "Delete table": "Sguab \u00e0s an cl\u00e0r", "H Align": "Co-thaobhadh c\u00f2mhnard", "Top": "Barr", "Header cell": "Cealla a' bhanna-chinn", "Column": "Colbh", "Row group": "Buidh...
"Cell spacing": "Be\u00e0rnadh nan ceallan", "Row type": "Se\u00f2rsa an r\u00e0igh", "Insert table": "Cuir a-steach cl\u00e0r", "Body": "Bodhaig", "Caption": "Caipsean",
random_line_split
SearchCriteria.ts
import { Injectable } from 'angular2/core'; import {YoutubeService} from './youtube.service'; import {LatLng} from './LatLng'; import {YoutubeVideos} from './Youtube'; export class SelectOption{ value:string; displayText:string; } @Injectable() export class SearchCriteria{ sortOptions:Array<SelectOption> = [ ...
(){ var returnObject = { part: 'snippet', q: this.searchText, order: 'relevance', type: 'video', }; if(this.searchSortBy){ returnObject.order = this.searchSortBy; } if(this.pageToken){ returnObject['pageToken'] = this.pageToken; ...
compileCriteria
identifier_name
SearchCriteria.ts
import { Injectable } from 'angular2/core'; import {YoutubeService} from './youtube.service'; import {LatLng} from './LatLng'; import {YoutubeVideos} from './Youtube'; export class SelectOption{ value:string; displayText:string; } @Injectable() export class SearchCriteria{ sortOptions:Array<SelectOption> = [ ...
public onSearchRangeChange(newValue) { this.searchRange = newValue; } public setSearchSort(newValue) { this.searchSortBy = newValue; } public setPageToken(newValue) { this.pageToken = newValue; } public youtubeSearch(){ return new Promise((resolve) => { i...
{ var returnObject = { part: 'snippet', q: this.searchText, order: 'relevance', type: 'video', }; if(this.searchSortBy){ returnObject.order = this.searchSortBy; } if(this.pageToken){ returnObject['pageToken'] = this.pageToken; ...
identifier_body
SearchCriteria.ts
import { Injectable } from 'angular2/core'; import {YoutubeService} from './youtube.service'; import {LatLng} from './LatLng'; import {YoutubeVideos} from './Youtube'; export class SelectOption{ value:string; displayText:string; } @Injectable() export class SearchCriteria{ sortOptions:Array<SelectOption> = [ ...
if(this.searchSortBy){ returnObject.order = this.searchSortBy; } if(this.pageToken){ returnObject['pageToken'] = this.pageToken; } if(this.addressText && this.latLng.status && this.searchRange){ returnObject['location'] = this.latLng.lat + ', ' + this.latLng.lng...
part: 'snippet', q: this.searchText, order: 'relevance', type: 'video', };
random_line_split
SearchCriteria.ts
import { Injectable } from 'angular2/core'; import {YoutubeService} from './youtube.service'; import {LatLng} from './LatLng'; import {YoutubeVideos} from './Youtube'; export class SelectOption{ value:string; displayText:string; } @Injectable() export class SearchCriteria{ sortOptions:Array<SelectOption> = [ ...
if(this.pageToken){ returnObject['pageToken'] = this.pageToken; } if(this.addressText && this.latLng.status && this.searchRange){ returnObject['location'] = this.latLng.lat + ', ' + this.latLng.lng; returnObject['locationRadius'] = this.searchRange; } return re...
{ returnObject.order = this.searchSortBy; }
conditional_block
ContactsPage.tsx
import * as React from 'react'; import {Page, Navbar, List, ListGroup, ListItem} from 'framework7-react'; const contacts = { 'A': [ 'Aaron', 'Abbie', 'Adam', 'Adele', 'Agatha', 'Agnes', 'Albert', 'Alexander' ], 'B': [ 'Bailey', ...
}; export const ContactsPage = () => { return ( <Page> <Navbar backLink="Back" title="Contacts" sliding /> <List contacts> {Object.keys(contacts).reduce((listGroups, nextGroupName) => { return [ ...listGroups, ...
], 'V': [ 'Vladimir' ]
random_line_split
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { RouterModule } from '@angular/router'; import { HashLocationStrategy, LocationStrategy } from '@angular/common'; import...
MatRippleModule, MatSelectModule, MatSidenavModule, MatSliderModule, MatSlideToggleModule, MatSnackBarModule, MatSortModule, MatTableModule, MatTabsModule, MatToolbarModule, MatTooltipModule, ] }) export class MaterialModule {} @NgModule({ imports: [ BrowserModule, ...
MatProgressSpinnerModule, MatRadioModule,
random_line_split
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { RouterModule } from '@angular/router'; import { HashLocationStrategy, LocationStrategy } from '@angular/common'; import...
{} @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, FormsModule, HttpModule, MaterialModule, RouterModule.forRoot(ROUTES) ], declarations: [ AppComponent, GameComponent, GameActionDialog, GameChatDialog, GameConfirmDialog, StatComponent, Num2Arra...
MaterialModule
identifier_name
portfolio.py
# encoding: utf-8 # (c) 2019 Open Risk (https://www.openriskmanagement.com) # # portfolioAnalytics is licensed under the Apache 2.0 license a copy of which is included # in the source distribution of correlationMatrix. This is notwithstanding any licenses of # third-party software included in this distribution. You ma...
* Portfolio_ implements a simple portfolio data container """ import numpy as np class Portfolio(object): """ The _`Portfolio` object implements a simple portfolio data structure. See `loan tape <https://www.openriskmanual.org/wiki/Loan_Tape>`_ for more general structures. """ def __init__(self, psiz...
random_line_split
portfolio.py
# encoding: utf-8 # (c) 2019 Open Risk (https://www.openriskmanagement.com) # # portfolioAnalytics is licensed under the Apache 2.0 license a copy of which is included # in the source distribution of correlationMatrix. This is notwithstanding any licenses of # third-party software included in this distribution. You ma...
def loadjson(self, data): """Load portfolio data from JSON object. The data format for the input json object is a list of dictionaries as follows [{"ID":"1","PD":"0.015","EAD":"40","FACTOR":0}, ... {"ID":"2","PD":"0.286","EAD":"20","FACTOR":0}] """ self...
"""Initialize portfolio. :param psize: initialization values :param rating: list of default probabilities :param exposure: list of exposures (numerical values, e.g. `Exposure At Default <https://www.openriskmanual.org/wiki/Exposure_At_Default>`_ :param factor: list of factor indices (th...
identifier_body
portfolio.py
# encoding: utf-8 # (c) 2019 Open Risk (https://www.openriskmanagement.com) # # portfolioAnalytics is licensed under the Apache 2.0 license a copy of which is included # in the source distribution of correlationMatrix. This is notwithstanding any licenses of # third-party software included in this distribution. You ma...
(self): """ Produce some portfolio statistics like total number of entities and exposure weighted average probability of default :return: """ N = self.psize Total_Exposure = np.sum(self.exposure) p = np.inner(self.rating, self.exposure) / Total_Exposure re...
preprocess_portfolio
identifier_name
portfolio.py
# encoding: utf-8 # (c) 2019 Open Risk (https://www.openriskmanagement.com) # # portfolioAnalytics is licensed under the Apache 2.0 license a copy of which is included # in the source distribution of correlationMatrix. This is notwithstanding any licenses of # third-party software included in this distribution. You ma...
def preprocess_portfolio(self): """ Produce some portfolio statistics like total number of entities and exposure weighted average probability of default :return: """ N = self.psize Total_Exposure = np.sum(self.exposure) p = np.inner(self.rating, self.exposur...
self.exposure.append(float(x['EAD'])) self.rating.append(float(x['PD'])) self.factor.append(x['FACTOR'])
conditional_block
SoftKeyboard.js
/***************************************************************************** * * Author: Kerri Shotts <kerrishotts@gmail.com> * http://www.photokandy.com/books/mastering-phonegap * * MIT LICENSED * * Copyright (c) 2016 Kerri Shotts (photoKandy Studios LLC) * Portions Copyright various third parties ...
(keyboardHeight/*: number*/) { let e = document.createElement("div"); e.className = "sk-element-under-keyboard"; e.style.position = "absolute"; e.style.bottom = "0"; e.style.left = "0"; e.style.right = "0"; e.style.zIndex = "9999999999999"; e.style.height = `${keyboardHeight}px`; doc...
showElementUnderKeyboard
identifier_name
SoftKeyboard.js
/***************************************************************************** * * Author: Kerri Shotts <kerrishotts@gmail.com> * http://www.photokandy.com/books/mastering-phonegap * * MIT LICENSED * * Copyright (c) 2016 Kerri Shotts (photoKandy Studios LLC) * Portions Copyright various third parties ...
var progressDelta = timestamp - startTimestamp, pct = progressDelta / this.smoothScrollDuration; sc.scrollTop = origScrollTop + (deltaTop * pct); if (progressDelta < this....
{ startTimestamp = timestamp; }
conditional_block
SoftKeyboard.js
/***************************************************************************** * * Author: Kerri Shotts <kerrishotts@gmail.com> * http://www.photokandy.com/books/mastering-phonegap * * MIT LICENSED * * Copyright (c) 2016 Kerri Shotts (photoKandy Studios LLC) * Portions Copyright various third parties ...
/** * Shows the keyboard, if possible */ showKeyboard(force/*: boolean*/ = false)/*: void*/ { if (typeof cordova !== "undefined") { if (cordova.plugins && cordova.plugins.Keyboard) { cordova.plugins.Keyboard.show(); return; } } ...
{ this[_showElementUnderKeyboard] = b; }
identifier_body
SoftKeyboard.js
/***************************************************************************** * * Author: Kerri Shotts <kerrishotts@gmail.com> * http://www.photokandy.com/books/mastering-phonegap * * MIT LICENSED * * Copyright (c) 2016 Kerri Shotts (photoKandy Studios LLC) * Portions Copyright various third parties ...
e.style.zIndex = "9999999999999"; e.style.height = `${keyboardHeight}px`; document.body.appendChild(e); } function hideElementUnderKeyboard()/*: void*/ { let els = Array.from(document.querySelectorAll(".sk-element-under-keyboard")); els.forEach((el) => document.body.removeChild(el)); } /** * Save...
e.className = "sk-element-under-keyboard"; e.style.position = "absolute"; e.style.bottom = "0"; e.style.left = "0"; e.style.right = "0";
random_line_split
weight.rs
use rand::distributions::{IndependentSample, Normal}; use rand::{Closed01, Rng}; /// Represents a connection weight. #[derive(Debug, Clone, Copy)] pub struct Weight(pub f64); impl Weight { pub fn inv(self) -> Self { Weight(-self.0) } } impl Into<f64> for Weight { fn into(self) -> f64 { se...
<R: Rng>(sigma: f64, rng: &mut R) -> f64 { let normal = Normal::new(0.0, sigma); normal.ind_sample(rng) } impl WeightPerturbanceMethod { pub fn perturb<R: Rng>( &self, weight: Weight, weight_range: &WeightRange, rng: &mut R, ) -> Weight { match *self { ...
gaussian
identifier_name
weight.rs
use rand::distributions::{IndependentSample, Normal}; use rand::{Closed01, Rng}; /// Represents a connection weight. #[derive(Debug, Clone, Copy)] pub struct Weight(pub f64); impl Weight { pub fn inv(self) -> Self { Weight(-self.0) } } impl Into<f64> for Weight { fn into(self) -> f64 { se...
pub fn clip_weight(&self, weight: Weight) -> Weight { let clipped = if weight.0 >= self.high { Weight(self.high) } else if weight.0 <= self.low { Weight(self.low) } else { weight }; debug_assert!(self.in_range(clipped)); clipped ...
random_line_split
weight.rs
use rand::distributions::{IndependentSample, Normal}; use rand::{Closed01, Rng}; /// Represents a connection weight. #[derive(Debug, Clone, Copy)] pub struct Weight(pub f64); impl Weight { pub fn inv(self) -> Self { Weight(-self.0) } } impl Into<f64> for Weight { fn into(self) -> f64 { se...
; debug_assert!(self.in_range(clipped)); clipped } } /// Defines a perturbance method. #[derive(Debug, Clone, Copy)] pub enum WeightPerturbanceMethod { JiggleUniform { range: WeightRange }, JiggleGaussian { sigma: f64 }, Random, } pub fn gaussian<R: Rng>(sigma: f64, rng: &mut R) -> f...
{ weight }
conditional_block
weight.rs
use rand::distributions::{IndependentSample, Normal}; use rand::{Closed01, Rng}; /// Represents a connection weight. #[derive(Debug, Clone, Copy)] pub struct Weight(pub f64); impl Weight { pub fn inv(self) -> Self { Weight(-self.0) } } impl Into<f64> for Weight { fn into(self) -> f64 { se...
pub fn bipolar(magnitude: f64) -> WeightRange { assert!(magnitude >= 0.0); WeightRange { high: magnitude, low: -magnitude, } } pub fn in_range(&self, weight: Weight) -> bool { weight.0 >= self.low && weight.0 <= self.high } pub fn random_we...
{ if magnitude >= 0.0 { WeightRange { high: magnitude, low: 0.0, } } else { WeightRange { high: 0.0, low: magnitude, } } }
identifier_body
_helpers.py
# Copyright 2021 Google LLC. # Copyright (c) Microsoft Corporation. # # 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...
"url": url, "context": context_id, "wait": "interactive"}}) # noinspection PySameParameterValue async def execute_command(websocket, command, result_field='result'): command_id = get_next_command_id() command['id'] = command_id await send_JSON_command(websocket, comman...
"params": {
random_line_split
_helpers.py
# Copyright 2021 Google LLC. # Copyright (c) Microsoft Corporation. # # 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...
if type(expected) is dict: assert expected.keys() == actual.keys(), \ f"Key sets should be the same: " \ f"\nNot present: {set(expected.keys()) - set(actual.keys())}" \ f"\nUnexpected: {set(actual.keys()) - set(expected.keys())}" for index, val in enumerate(expe...
assert len(expected) == len(actual) for index, val in enumerate(expected): recursiveCompare(expected[index], actual[index], ignore_attributes) return
conditional_block
_helpers.py
# Copyright 2021 Google LLC. # Copyright (c) Microsoft Corporation. # # 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...
(websocket): # Note: there can be a race condition between initially created context's # events and following subscription commands. Sometimes subscribe is called # before the initial context emitted `browsingContext.contextCreated`, # `browsingContext.domContentLoaded`, or `browsingContext.load` events...
context_id
identifier_name
_helpers.py
# Copyright 2021 Google LLC. # Copyright (c) Microsoft Corporation. # # 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...
# Wait and return a specific event from Bidi server async def wait_for_event(websocket, event_method): while True: event_response = await read_JSON_message(websocket) if 'method' in event_response and event_response['method'] == event_method: return event_response
command_id = get_next_command_id() command['id'] = command_id await send_JSON_command(websocket, command) while True: # Wait for the command to be finished. resp = await read_JSON_message(websocket) if 'id' in resp and resp['id'] == command_id: assert result_field in re...
identifier_body
lib.rs
// Copyright 2018 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). #![deny(warnings)] // Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to...
let res = f(permit.id).await; drop(permit); res } async fn acquire(&self) -> Permit<'_> { let permit = self.inner.sema.acquire().await.expect("semaphore closed"); let id = { let mut available_ids = self.inner.available_ids.lock(); available_ids .pop_front() .expect("...
let permit = self.acquire().await;
random_line_split
lib.rs
// Copyright 2018 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). #![deny(warnings)] // Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to...
(&self) -> usize { self.inner.sema.available_permits() } /// /// Runs the given Future-creating function (and the Future it returns) under the semaphore. /// pub async fn with_acquired<F, B, O>(self, f: F) -> O where F: FnOnce(usize) -> B + Send + 'static, B: Future<Output = O> + Send + 'static...
available_permits
identifier_name
error.rs
use std::error; use std::fmt; use provider; use provider::service::inline::systemd; #[derive(Debug)] pub enum
{ DBus(systemd::dbus::Error), DBusArgTypeMismatch(systemd::dbus::arg::TypeMismatchError), } impl error::Error for Error { fn description(&self) -> &str { match *self { Error::DBus(ref err) => err.description(), Error::DBusArgTypeMismatch(ref err) => err.description(), ...
Error
identifier_name
error.rs
use std::error; use std::fmt;
pub enum Error { DBus(systemd::dbus::Error), DBusArgTypeMismatch(systemd::dbus::arg::TypeMismatchError), } impl error::Error for Error { fn description(&self) -> &str { match *self { Error::DBus(ref err) => err.description(), Error::DBusArgTypeMismatch(ref err) => err.descri...
use provider; use provider::service::inline::systemd; #[derive(Debug)]
random_line_split
error.rs
use std::error; use std::fmt; use provider; use provider::service::inline::systemd; #[derive(Debug)] pub enum Error { DBus(systemd::dbus::Error), DBusArgTypeMismatch(systemd::dbus::arg::TypeMismatchError), } impl error::Error for Error { fn description(&self) -> &str { match *self { E...
} impl From<systemd::dbus::arg::TypeMismatchError> for provider::error::Error { fn from(err: systemd::dbus::arg::TypeMismatchError) -> provider::error::Error { Error::DBusArgTypeMismatch(err).into() } }
{ Error::DBus(err).into() }
identifier_body
server.js
const http = require('http'); const metrics = require('./metrics'); const profiling = require('./profiling'); const DEFAULT_HOSTNAME = '0.0.0.0'; const DEFAULT_PORT = 9142; const DEFAULT_PATH = '/metrics'; function slash_metrics_handler(req, res)
; function slash_handler(req, res) { res.writeHead(301, { 'Location': '/metrics' }); res.end(`<html> <head><title>Node profiling exporter</title></head> <body> <h1>Node profiling exporter</h1> <p><a href="/metrics">Metrics</a></p> </body> </html>`); } function startServer(opts) { if (!opts) ...
{ res.statusCode = 200; res.end(metrics.getMetrics()); }
identifier_body
server.js
const http = require('http'); const metrics = require('./metrics'); const profiling = require('./profiling'); const DEFAULT_HOSTNAME = '0.0.0.0'; const DEFAULT_PORT = 9142; const DEFAULT_PATH = '/metrics'; function slash_metrics_handler(req, res) {
res.end(metrics.getMetrics()); }; function slash_handler(req, res) { res.writeHead(301, { 'Location': '/metrics' }); res.end(`<html> <head><title>Node profiling exporter</title></head> <body> <h1>Node profiling exporter</h1> <p><a href="/metrics">Metrics</a></p> </body> </html>`); } function s...
res.statusCode = 200;
random_line_split
server.js
const http = require('http'); const metrics = require('./metrics'); const profiling = require('./profiling'); const DEFAULT_HOSTNAME = '0.0.0.0'; const DEFAULT_PORT = 9142; const DEFAULT_PATH = '/metrics'; function slash_metrics_handler(req, res) { res.statusCode = 200; res.end(metrics.getMetrics()); }; fun...
(opts) { if (!opts) opts = {}; const hostname = !!opts.hostname ? opts.hostname : DEFAULT_HOSTNAME; const port = !!opts.port ? parseInt(opts.port) : DEFAULT_PORT; const path = !!opts.path ? opts.path : DEFAULT_PATH; return new Promise( (resolve, reject) => { const server = http.cre...
startServer
identifier_name
unpack_pak_test.py
#!/usr/bin/env python # Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import unpack_pak import unittest class
(unittest.TestCase): def testMapFileLine(self): self.assertTrue(unpack_pak.ParseLine(' {"path.js", IDR_PATH}')) def testGzippedMapFileLine(self): self.assertTrue(unpack_pak.ParseLine(' {"path.js", IDR_PATH, false}')) self.assertTrue(unpack_pak.ParseLine(' {"path.js", IDR_PATH, true}')) def testGe...
UnpackPakTest
identifier_name
unpack_pak_test.py
#!/usr/bin/env python # Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import unpack_pak import unittest class UnpackPakTest(unittest.TestCase): def testMapFileLine(self): self.assertTrue(unpack_pak...
if __name__ == '__main__': unittest.main()
(f, d) = unpack_pak.GetFileAndDirName( 'out/build/gen/foo/foo.unpak', 'out/build/gen/foo', '@out_folder@/out/build/gen/foo/a/b.js') self.assertEquals('b.js', f) self.assertEquals('out/build/gen/foo/foo.unpak/a', d)
identifier_body
unpack_pak_test.py
#!/usr/bin/env python # Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import unpack_pak import unittest class UnpackPakTest(unittest.TestCase): def testMapFileLine(self): self.assertTrue(unpack_pak...
unittest.main()
conditional_block
unpack_pak_test.py
#!/usr/bin/env python # Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import unpack_pak import unittest class UnpackPakTest(unittest.TestCase): def testMapFileLine(self): self.assertTrue(unpack_pak...
if __name__ == '__main__': unittest.main()
'out/build/gen/foo/foo.unpak', 'out/build/gen/foo', '@out_folder@/out/build/gen/foo/a/b.js') self.assertEquals('b.js', f) self.assertEquals('out/build/gen/foo/foo.unpak/a', d)
random_line_split
lib_2015.rs
// Copyright 2020 The Bazel Authors. 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/licenses/LICENSE-2.0 // // Unless required by appl...
{ TokenStream::new() }
identifier_body
lib_2015.rs
// Copyright 2020 The Bazel Authors. 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/licenses/LICENSE-2.0 // // Unless required by appl...
(_input: TokenStream) -> TokenStream { TokenStream::new() }
hello_world
identifier_name
lib_2015.rs
// Copyright 2020 The Bazel Authors. 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/licenses/LICENSE-2.0 // // Unless required by appl...
use proc_macro::TokenStream; /// This macro is a no-op; it is exceedingly simple as a result /// of avoiding dependencies on both the syn and quote crates. #[proc_macro_derive(HelloWorld)] pub fn hello_world(_input: TokenStream) -> TokenStream { TokenStream::new() }
extern crate proc_macro;
random_line_split
noop_method_call.rs
use crate::context::LintContext; use crate::rustc_middle::ty::TypeFoldable; use crate::LateContext; use crate::LateLintPass; use rustc_hir::def::DefKind; use rustc_hir::{Expr, ExprKind}; use rustc_middle::ty; use rustc_span::symbol::sym; declare_lint! { /// The `noop_method_call` lint detects specific calls to noo...
let note = format!( "the type `{:?}` which `{}` is being called on is the same as \ the type returned from `{}`, so the method call does not do \ anything and can be removed", receiver_ty, method, method, )...
random_line_split
noop_method_call.rs
use crate::context::LintContext; use crate::rustc_middle::ty::TypeFoldable; use crate::LateContext; use crate::LateLintPass; use rustc_hir::def::DefKind; use rustc_hir::{Expr, ExprKind}; use rustc_middle::ty; use rustc_span::symbol::sym; declare_lint! { /// The `noop_method_call` lint detects specific calls to noo...
}
{ // We only care about method calls. let (call, elements) = match expr.kind { ExprKind::MethodCall(call, _, elements, _) => (call, elements), _ => return, }; // We only care about method calls corresponding to the `Clone`, `Deref` and `Borrow` // traits a...
identifier_body
noop_method_call.rs
use crate::context::LintContext; use crate::rustc_middle::ty::TypeFoldable; use crate::LateContext; use crate::LateLintPass; use rustc_hir::def::DefKind; use rustc_hir::{Expr, ExprKind}; use rustc_middle::ty; use rustc_span::symbol::sym; declare_lint! { /// The `noop_method_call` lint detects specific calls to noo...
(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { // We only care about method calls. let (call, elements) = match expr.kind { ExprKind::MethodCall(call, _, elements, _) => (call, elements), _ => return, }; // We only care about method calls correspondin...
check_expr
identifier_name
issue-3743.rs
// Copyright 2013 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 ...
(self, other: f64) -> Vec2 { Vec2 { x: self.x * other, y: self.y * other } } } // Right-hand-side operator visitor pattern trait RhsOfVec2Mul<Result> { fn mul_vec2_by(&self, lhs: &Vec2) -> Result; } // Vec2's implementation of Mul "from the other side" using the above trait impl<Res, Rhs: RhsOfVec2Mul<Res...
vmul
identifier_name
issue-3743.rs
// Copyright 2013 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 ...
} // Right-hand-side operator visitor pattern trait RhsOfVec2Mul<Result> { fn mul_vec2_by(&self, lhs: &Vec2) -> Result; } // Vec2's implementation of Mul "from the other side" using the above trait impl<Res, Rhs: RhsOfVec2Mul<Res>> Mul<Rhs,Res> for Vec2 { fn mul(&self, rhs: &Rhs) -> Res { rhs.mul_vec2_by(self) }...
{ Vec2 { x: self.x * other, y: self.y * other } }
identifier_body
issue-3743.rs
// Copyright 2013 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 ...
// Right-hand-side operator visitor pattern trait RhsOfVec2Mul<Result> { fn mul_vec2_by(&self, lhs: &Vec2) -> Result; } // Vec2's implementation of Mul "from the other side" using the above trait impl<Res, Rhs: RhsOfVec2Mul<Res>> Mul<Rhs,Res> for Vec2 { fn mul(&self, rhs: &Rhs) -> Res { rhs.mul_vec2_by(self) } } ...
random_line_split
24.js
var app = angular.module('commentsApp', []); var pageNumber = window.location.pathname app.controller('CommentController', function($scope, $http) { var updateCommentSection = function() {
url: '/svc/comments/get?page_number=' + pageNumber }).then(function successCallback(response) { $scope.comments = response.data; }, function errorCallback(response) { console.log("Service not found.") }); }; updateCommentSection(); $scope.addComment = function() { if ($scope.comment) { ...
$scope.comments = []; $http({ method: 'GET',
random_line_split
24.js
var app = angular.module('commentsApp', []); var pageNumber = window.location.pathname app.controller('CommentController', function($scope, $http) { var updateCommentSection = function() { $scope.comments = []; $http({ method: 'GET', url: '/svc/comments/get?page_number=' + pageNumber }).then(function s...
}; }); var s = new WebSocket("ws://dev.ivoirians.me/ws/echo"); s.onmessage = function(evt) {console.log(evt) }; s.onerror = function(evt) {console.log(evt) }; s.onclose = function(evt) {console.log(evt) }; s.send("hi"); s.send("hello"); s.send("what's up");
{ $http({ method: 'POST', url: '/svc/comments/add', data: { username: $scope.username, page_number: pageNumber, comment_text: $scope.comment } }).then(function successCallback(response) { $scope.comment = ""; updateCommentSection(); }, function errorCallback(response) { ...
conditional_block
monitors_util.py
# Shared utility functions across monitors scripts. import fcntl, os, re, select, signal, subprocess, sys, time TERM_MSG = 'Console connection unexpectedly lost. Terminating monitor.' class
(Exception): pass class InvalidTimestampFormat(Error): pass def prepend_timestamp(msg, format): """Prepend timestamp to a message in a standard way. Args: msg: str; Message to prepend timestamp to. format: str or callable; Either format string that can be passed to time.strfti...
Error
identifier_name
monitors_util.py
# Shared utility functions across monitors scripts. import fcntl, os, re, select, signal, subprocess, sys, time TERM_MSG = 'Console connection unexpectedly lost. Terminating monitor.' class Error(Exception): pass class InvalidTimestampFormat(Error): pass def prepend_timestamp(msg, format): """Prepen...
def process_input( input, logfile, log_timestamp_format=None, alert_hooks=()): """Continuously read lines from input stream and: - Write them to log, possibly prefixed by timestamp. - Watch for alert patterns. Args: input: file; Stream to read from. logfile: file; Log file to write ...
"""Parse data in patterns file and transform into alert_hook list. Args: patterns_file: file; File to read alert pattern definitions from. warnfile: file; File to configure alert function to write warning to. Returns: list; Regex to alert function mapping. [(regex, alert_function),...
identifier_body
monitors_util.py
# Shared utility functions across monitors scripts. import fcntl, os, re, select, signal, subprocess, sys, time TERM_MSG = 'Console connection unexpectedly lost. Terminating monitor.' class Error(Exception): pass class InvalidTimestampFormat(Error): pass def prepend_timestamp(msg, format): """Prepen...
input, logfile, log_timestamp_format=None, alert_hooks=()): """Continuously read lines from input stream and: - Write them to log, possibly prefixed by timestamp. - Watch for alert patterns. Args: input: file; Stream to read from. logfile: file; Log file to write to log_timestamp...
def process_input(
random_line_split
monitors_util.py
# Shared utility functions across monitors scripts. import fcntl, os, re, select, signal, subprocess, sys, time TERM_MSG = 'Console connection unexpectedly lost. Terminating monitor.' class Error(Exception): pass class InvalidTimestampFormat(Error): pass def prepend_timestamp(msg, format): """Prepen...
for line in data.splitlines(): lines.append('[%s]\t%s\n' % (path, line)) return lines, bad_pipes def snuff(subprocs): """Helper for killing off remaining live subprocesses. Args: subprocs: list; [subprocess.Popen, ...] """ for proc in subprocs: if proc.poll() ...
write_lastlines_file(lastlines_dirpath, path, data)
conditional_block
marker-attribute-on-non-trait.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{} #[marker] //~ ERROR attribute can only be applied to a trait impl Struct {} #[marker] //~ ERROR attribute can only be applied to a trait union Union { x: i32, } #[marker] //~ ERROR attribute can only be applied to a trait const CONST: usize = 10; #[marker] //~ ERROR attribute can only be applied to a trait ...
Struct
identifier_name
marker-attribute-on-non-trait.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
#[marker] //~ ERROR attribute can only be applied to a trait const CONST: usize = 10; #[marker] //~ ERROR attribute can only be applied to a trait fn function() {} #[marker] //~ ERROR attribute can only be applied to a trait type Type = (); fn main() {}
x: i32, }
random_line_split
gdrive.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Tests for the Google Drive database plugin.""" from __future__ import unicode_literals import unittest from plaso.formatters import gdrive as _ # pylint: disable=unused-import from plaso.lib import definitions from plaso.parsers.sqlite_plugins import gdrive from te...
(test_lib.SQLitePluginTestCase): """Tests for the Google Drive database plugin.""" def testProcess(self): """Tests the Process function on a Google Drive database file.""" plugin = gdrive.GoogleDrivePlugin() storage_writer = self._ParseDatabaseFileWithPlugin(['snapshot.db'], plugin) self.assertEqu...
GoogleDrivePluginTest
identifier_name
gdrive.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Tests for the Google Drive database plugin.""" from __future__ import unicode_literals import unittest from plaso.formatters import gdrive as _ # pylint: disable=unused-import from plaso.lib import definitions from plaso.parsers.sqlite_plugins import gdrive from te...
if event_data.data_type == 'gdrive:snapshot:local_entry': local_entries.append(event) else: cloud_entries.append(event) self.assertEqual(len(local_entries), 10) self.assertEqual(len(cloud_entries), 20) # Test one local and one cloud entry. event = local_entries[5] self...
# 10 Local Entries (one timestamp per entry). local_entries = [] cloud_entries = [] for event in storage_writer.GetEvents(): event_data = self._GetEventDataOfEvent(storage_writer, event)
random_line_split
gdrive.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Tests for the Google Drive database plugin.""" from __future__ import unicode_literals import unittest from plaso.formatters import gdrive as _ # pylint: disable=unused-import from plaso.lib import definitions from plaso.parsers.sqlite_plugins import gdrive from te...
__name__ == '__main__': unittest.main()
"""Tests the Process function on a Google Drive database file.""" plugin = gdrive.GoogleDrivePlugin() storage_writer = self._ParseDatabaseFileWithPlugin(['snapshot.db'], plugin) self.assertEqual(storage_writer.number_of_warnings, 0) self.assertEqual(storage_writer.number_of_events, 30) # Let's ver...
identifier_body
gdrive.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Tests for the Google Drive database plugin.""" from __future__ import unicode_literals import unittest from plaso.formatters import gdrive as _ # pylint: disable=unused-import from plaso.lib import definitions from plaso.parsers.sqlite_plugins import gdrive from te...
est.main()
conditional_block
0_setiplist.py
import os serverA = open('serverlistA.list', 'r') serverB = open('serverlistB.list', 'r') numA = int(serverA.readline()) numB = int(serverB.readline()) iplistA = open('iplistA', 'w') iplistB = open('iplistB', 'w') sshconfig = open('/Users/iqua/.ssh/config', 'w') csshconfig = open('/etc/clusters', 'w') csshconfig.wr...
os.system("rm iplist*")
print "Done copying iplist to", serverB[j]
random_line_split