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
setup.py
# Copyright 2017 The TensorFlow 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 applica...
long_description='Tools for capture TPU profile', url='https://www.tensorflow.org/tfrc/', author='Google Inc.', author_email='opensource@google.com', packages=['cloud_tpu_profiler'], package_data={ 'cloud_tpu_profiler': ['data/*'], }, entry_points={ 'console_scripts': CON...
version=_VERSION.replace('-', ''), description='Trace and profile Cloud TPU performance',
random_line_split
test_dep_graph.py
from __future__ import unicode_literals from rbpkg.package_manager.dep_graph import DependencyGraph from rbpkg.testing.testcases import TestCase class DependencyGraphTests(TestCase): """Unit tests for rbpkg.package_manager.dep_graph.DependencyGraph.""" def test_iter_sorted_simple(self): """Testing D...
self.assertEqual(list(graph.iter_sorted()), [14, 20, 9, 5, 2, 6, 15, 12]) def test_iter_sorted_circular_ref(self): """Testing DependencyGraph.iter_sorted with circular reference""" graph = DependencyGraph() graph.add(1, [2]) graph.add(2, [1]) ...
random_line_split
test_dep_graph.py
from __future__ import unicode_literals from rbpkg.package_manager.dep_graph import DependencyGraph from rbpkg.testing.testcases import TestCase class DependencyGraphTests(TestCase): """Unit tests for rbpkg.package_manager.dep_graph.DependencyGraph.""" def test_iter_sorted_simple(self):
def test_iter_sorted_complex(self): """Testing DependencyGraph.iter_sorted with complex dependencies""" graph = DependencyGraph() graph.add(5, [9]) graph.add(12, [9, 6, 15]) graph.add(15, [9, 2]) graph.add(9, [14, 20]) graph.add(6, [14, 2]) self.ass...
"""Testing DependencyGraph.iter_sorted in simple case""" graph = DependencyGraph() graph.add(3, [2]) graph.add(2, [1]) graph.add(1, []) self.assertEqual(list(graph.iter_sorted()), [1, 2, 3])
identifier_body
test_dep_graph.py
from __future__ import unicode_literals from rbpkg.package_manager.dep_graph import DependencyGraph from rbpkg.testing.testcases import TestCase class DependencyGraphTests(TestCase): """Unit tests for rbpkg.package_manager.dep_graph.DependencyGraph.""" def
(self): """Testing DependencyGraph.iter_sorted in simple case""" graph = DependencyGraph() graph.add(3, [2]) graph.add(2, [1]) graph.add(1, []) self.assertEqual(list(graph.iter_sorted()), [1, 2, 3]) def test_iter_sorted_complex(self): """Testing DependencyGr...
test_iter_sorted_simple
identifier_name
idb-helper.js
let db; let idb_helper; module.exports = idb_helper = { set_graphene_db: database => { db = database; }, trx_readwrite: object_stores => { return db.transaction( [object_stores], "readwrite" ); }, on_request_end: (request) => { //return request => { ...
{ constructor(existing_on_event, callback, request) { this.event = (event)=> { if(event.target.error) console.error("---- transaction error ---->", event.target.error); //event.request = request callback(event); if(existing_on_event) existing_...
ChainEvent
identifier_name
idb-helper.js
let db; let idb_helper; module.exports = idb_helper = { set_graphene_db: database => { db = database; }, trx_readwrite: object_stores => { return db.transaction( [object_stores], "readwrite" ); }, on_request_end: (request) => { //return request => { ...
return db.createObjectStore( table_name, { keyPath: "id", autoIncrement: true } ).createIndex( "by_"+unique_index, unique_index, { unique: true } ); } }; class ChainEvent { constructor(existing_on_event, callback, request) { this.event = (event)=> { ...
autoIncrement_unique: (db, table_name, unique_index) => {
random_line_split
ip_ban.py
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Copyright 2013 Joe Harris 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 ...
from twisted.internet import reactor import txcloudflare def got_response(response): ''' 'response' is a txcloudflare.response.Response() instance. ''' print '< got a response (done)' print '< ip: {0}'.format(response.data.get('ip', '')) print '< action: {0}'.format(response.data.get('act...
sys.path.insert(0, txcfpath)
conditional_block
ip_ban.py
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Copyright 2013 Joe Harris 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 ...
(error): ''' 'error' is a twisted.python.failure.Failure() instance wrapping one of the exceptions in txcloudflare.errors. The exceptions return the CloudFlare error code, a plain text string and a response object (txcloudflare.response.Response). The response object has a 'request' ...
got_error
identifier_name
ip_ban.py
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Copyright 2013 Joe Harris 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 ...
def got_error(error): ''' 'error' is a twisted.python.failure.Failure() instance wrapping one of the exceptions in txcloudflare.errors. The exceptions return the CloudFlare error code, a plain text string and a response object (txcloudflare.response.Response). The response object h...
''' 'response' is a txcloudflare.response.Response() instance. ''' print '< got a response (done)' print '< ip: {0}'.format(response.data.get('ip', '')) print '< action: {0}'.format(response.data.get('action', '')) reactor.stop()
identifier_body
ip_ban.py
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Copyright 2013 Joe Harris 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 ...
EOF '''
random_line_split
api_request_builder.ts
/* * Copyright 2021 ThoughtWorks, 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 applicable law or agr...
header(name: string) { return this.headers.get(name); } getEtag(): string | null { return this.header("etag") || null; } getRedirectUrl(): string { return this.header("Location") || ""; } getRetryAfterIntervalInMillis(): number { return Number(this.header("retry-after") || 0) * 1000; ...
return this.statusCode; } return -1; }
random_line_split
api_request_builder.ts
/* * Copyright 2021 ThoughtWorks, 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 applicable law or agr...
(successResponse: SuccessResponse<T> | undefined, errorResponse: ErrorResponse | undefined, statusCode: number, headers: Map<string, string>) { this.successResponse = successResponse; this.errorResponse = errorResponse; this.statusCode ...
constructor
identifier_name
api_request_builder.ts
/* * Copyright 2021 ThoughtWorks, 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 applicable law or agr...
else { return `application/vnd.go.cd.${ApiVersion[version]}+json`; } } private static makeRequest(url: string, method: string, apiVersion?: ApiVersion, options?: Partial<RequestOptions>): Promise<ApiResult<string>> { ...
{ return `application/vnd.go.cd+json`; }
conditional_block
api_request_builder.ts
/* * Copyright 2021 ThoughtWorks, 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 applicable law or agr...
map<U>(func: (x: T) => U): ApiResult<U> { if (this.successResponse) { const transformedBody = func(this.successResponse.body); return new ApiResult<U>({body: transformedBody}, this.errorResponse, this.statusCode, this.headers); } else { return new ApiResult<U>(this.successResponse, this.er...
{ return Number(this.header("retry-after") || 0) * 1000; }
identifier_body
app.min.js
(function() { var MainView, stripTags, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor()
ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; stripTags = function(input, allowed) { var commentsAndPhpTags, tags; allowed = (((allowed || '') + '').toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join('...
{ this.constructor = child; }
identifier_body
app.min.js
(function() { var MainView, stripTags, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function
() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; stripTags = function(input, allowed) { var commentsAndPhpTags, tags; allowed = (((allowed || '') + '').toLowerCase().match(/<...
ctor
identifier_name
app.min.js
(function() { var MainView, stripTags, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return c...
return function() { if (_this.playButton.hasClass("stopButton")) { _this.playButton.unsetClass("stopButton fa-stop"); _this.playButton.setClass("playButton fa-play"); _this.playerLabel.updatePartial("---"); document.getElementById('audio-play...
random_line_split
app.min.js
(function() { var MainView, stripTags, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return c...
else { return ''; } }); }; KD.enableLogs; MainView = (function(superClass) { extend(MainView, superClass); function MainView() { MainView.__super__.constructor.apply(this, arguments); this.kite = KD.getSingleton("vmController"); this.header = new KDHeaderView({ ...
{ return $0; }
conditional_block
traits.rs
use image::{imageops, DynamicImage, GenericImageView, GrayImage, ImageBuffer, Pixel}; use std::borrow::Cow; use std::ops; /// Interface for types used for storing hash data. /// /// This is implemented for `Vec<u8>`, `Box<[u8]>` and arrays that are multiples/combinations of /// useful x86 bytewise SIMD register width...
default fn foreach_pixel8<F>(&self, mut foreach: F) where F: FnMut(u32, u32, &[u8]) { self.enumerate_pixels().for_each(|(x, y, px)| foreach(x, y, px.channels())) } } impl<P: 'static> DiffImage for ImageBuffer<P, Vec<u8>> where P: Pixel<Subpixel = u8> { fn diff_inplace(&mut self, other: &Self) { ...
{ imageops::blur(self, sigma) }
identifier_body
traits.rs
use image::{imageops, DynamicImage, GenericImageView, GrayImage, ImageBuffer, Pixel}; use std::borrow::Cow; use std::ops; /// Interface for types used for storing hash data. /// /// This is implemented for `Vec<u8>`, `Box<[u8]>` and arrays that are multiples/combinations of /// useful x86 bytewise SIMD register width...
else { upper / 8 + 1}) ) } } pub(crate) trait BitSet: HashBytes { fn from_bools<I: Iterator<Item = bool>>(iter: I) -> Self where Self: Sized { Self::from_iter(BoolsToBytes { iter }) } fn hamming(&self, other: &Self) -> u32 { self.as_slice().iter().zip(other.as_slice()).map(|(l...
{ upper / 8 }
conditional_block
traits.rs
use image::{imageops, DynamicImage, GenericImageView, GrayImage, ImageBuffer, Pixel}; use std::borrow::Cow; use std::ops; /// Interface for types used for storing hash data. /// /// This is implemented for `Vec<u8>`, `Box<[u8]>` and arrays that are multiples/combinations of /// useful x86 bytewise SIMD register width...
impl HashBytes for [u8; $n] { fn from_iter<I: Iterator<Item=u8>>(mut iter: I) -> Self { // optimizer should eliminate this zeroing let mut out = [0; $n]; for (src, dest) in iter.by_ref().zip(out.as_mut()) { *dest = src; ...
fn as_slice(&self) -> &[u8] { self } } macro_rules! hash_bytes_array { ($($n:expr),*) => {$(
random_line_split
traits.rs
use image::{imageops, DynamicImage, GenericImageView, GrayImage, ImageBuffer, Pixel}; use std::borrow::Cow; use std::ops; /// Interface for types used for storing hash data. /// /// This is implemented for `Vec<u8>`, `Box<[u8]>` and arrays that are multiples/combinations of /// useful x86 bytewise SIMD register width...
(&self, sigma: f32) -> Self::Buf { imageops::blur(self, sigma) } fn foreach_pixel8<F>(&self, mut foreach: F) where F: FnMut(u32, u32, &[u8]) { self.pixels().for_each(|(x, y, px)| foreach(x, y, px.channels())) } } #[cfg(feature = "nightly")] impl Image for GrayImage { // type Buf = GrayImage; ...
blur
identifier_name
basics.py
import functools import html import itertools import pprint from mondrian import term from bonobo import settings from bonobo.config import Configurable, Method, Option, use_context, use_no_input, use_raw_input from bonobo.config.functools import transformation_factory from bonobo.config.processors import ContextProc...
(self, counter, *args, **kwargs): counter += 1 if counter <= self.limit: yield NOT_MODIFIED def Tee(f): @functools.wraps(f) def wrapped(*args, **kwargs): nonlocal f f(*args, **kwargs) return NOT_MODIFIED return wrapped def _shorten(s, w): if w and...
__call__
identifier_name
basics.py
import functools import html import itertools import pprint from mondrian import term from bonobo import settings from bonobo.config import Configurable, Method, Option, use_context, use_no_input, use_raw_input from bonobo.config.functools import transformation_factory from bonobo.config.processors import ContextProc...
"FixedWindow", "Format", "Limit", "OrderFields", "MapFields", "PrettyPrinter", "Rename", "SetFields", "Tee", "UnpackItems", "count", "identity", "noop", ] def identity(x): return x class Limit(Configurable): """ Creates a Limit() node, that will only l...
from bonobo.errors import UnrecoverableAttributeError from bonobo.util.objects import ValueHolder from bonobo.util.term import CLEAR_EOL __all__ = [
random_line_split
basics.py
import functools import html import itertools import pprint from mondrian import term from bonobo import settings from bonobo.config import Configurable, Method, Option, use_context, use_no_input, use_raw_input from bonobo.config.functools import transformation_factory from bonobo.config.processors import ContextProc...
yield tuple(row.get(field) for field in context.get_output_fields()) return _OrderFields @transformation_factory def SetFields(fields): """ Transformation factory that sets the field names on first iteration, without touching the values. :param fields: :return: callable """ @u...
context.remaining = list(sorted(set(context.get_input_fields()) - set(fields))) context.set_output_fields(fields + context.remaining)
conditional_block
basics.py
import functools import html import itertools import pprint from mondrian import term from bonobo import settings from bonobo.config import Configurable, Method, Option, use_context, use_no_input, use_raw_input from bonobo.config.functools import transformation_factory from bonobo.config.processors import ContextProc...
@transformation_factory def Rename(**translations): # XXX todo handle duplicated fields = None translations = {v: k for k, v in translations.items()} @use_context @use_raw_input def _Rename(context, bag): nonlocal fields, translations if not fields: fields = tup...
""" >>> UnpackItems(0) :param items: :param fields: :param defaults: :return: callable """ defaults = defaults or {} @use_context @use_raw_input def _UnpackItems(context, bag): nonlocal fields, items, defaults if fields is None: fields = () ...
identifier_body
test_rocket1.py
from rocketlander import RocketLander from constants import LEFT_GROUND_CONTACT, RIGHT_GROUND_CONTACT import numpy as np import pyglet if __name__ == "__main__": # Settings holds all the settings for the rocket lander environment. settings = {'Side Engines': True, 'Clouds': True,
'Vectorized Nozzle': True, 'Starting Y-Pos Constant': 1, 'Initial Force': 'random'} # (6000, -10000)} env = RocketLander(settings) s = env.reset() left_or_right_barge_movement = np.random.randint(0, 2) for i in range(50): a = [10.0, 1....
random_line_split
test_rocket1.py
from rocketlander import RocketLander from constants import LEFT_GROUND_CONTACT, RIGHT_GROUND_CONTACT import numpy as np import pyglet if __name__ == "__main__": # Settings holds all the settings for the rocket lander environment. settings = {'Side Engines': True, 'Clouds': True, ...
env.draw_marker(env.landing_coordinates[0], env.landing_coordinates[1]) # Refresh render env.refresh(render=False) # When should the barge move? Water movement, dynamics etc can be simulated here. if s[LEFT_GROUND_CONTACT] == 0 and s[RIGHT_GROUN...
image_data.save(filename='frames/rocket-%04d.png' % i)
conditional_block
S12.14_A2.js
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S12.14_A2; * @section: 12.14; * @assertion: Throwing exception with "throw" and catching it with "try" statement; * @description: Checking if execution of "catch" catches...
{ $ERROR('#3.3: "finally" block must be evaluated'); }
conditional_block
S12.14_A2.js
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S12.14_A2; * @section: 12.14; * @assertion: Throwing exception with "throw" and catching it with "try" statement; * @description: Checking if execution of "catch" catches...
$ERROR('#2.1: throw "exc" lead to throwing exception'); }finally{ c2=1; } } catch(e){ if (c2!==1){ $ERROR('#2.2: "finally" block must be evaluated'); } } // CHECK#3 var c3=0; try{ throw "exc"; $ERROR('#3.1: throw "exc" lead to throwing exception'); } catch(err){ var x3=1; } finally{ c3=...
// CHECK#2 var c2=0; try{ try{ throw "exc";
random_line_split
time.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/. */ //! Specified time values. use cssparser::{Parser, Token}; use parser::{Parse, ParserContext}; use std::fmt::{sel...
{ seconds: CSSFloat, unit: TimeUnit, was_calc: bool, } /// A time unit. #[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq)] pub enum TimeUnit { /// `s` Second, /// `ms` Millisecond, } impl Time { /// Returns a time value that represents `seconds` seconds. pub fn from_seconds...
ime
identifier_name
time.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/. */ //! Specified time values. use cssparser::{Parser, Token}; use parser::{Parse, ParserContext}; use std::fmt::{sel...
unit: TimeUnit::Second, was_calc: false, } } /// Returns `0s`. pub fn zero() -> Self { Self::from_seconds(0.0) } /// Returns the time in fractional seconds. pub fn seconds(self) -> CSSFloat { self.seconds } /// Parses a time according to...
/// Returns a time value that represents `seconds` seconds. pub fn from_seconds(seconds: CSSFloat) -> Self { Time { seconds,
random_line_split
time.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/. */ //! Specified time values. use cssparser::{Parser, Token}; use parser::{Parse, ParserContext}; use std::fmt::{sel...
/// Returns a `Time` value from a CSS `calc()` expression. pub fn from_calc(seconds: CSSFloat) -> Self { Time { seconds: seconds, unit: TimeUnit::Second, was_calc: true, } } fn parse_with_clamping_mode<'i, 't>( context: &ParserContext, ...
let (seconds, unit) = match_ignore_ascii_case! { unit, "s" => (value, TimeUnit::Second), "ms" => (value / 1000.0, TimeUnit::Millisecond), _ => return Err(()) }; Ok(Time { seconds, unit, was_calc, }) }
identifier_body
time.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/. */ //! Specified time values. use cssparser::{Parser, Token}; use parser::{Parse, ParserContext}; use std::fmt::{sel...
match self.unit { TimeUnit::Second => { self.seconds.to_css(dest)?; dest.write_str("s")?; }, TimeUnit::Millisecond => { (self.seconds * 1000.).to_css(dest)?; dest.write_str("ms")?; }, } ...
dest.write_str("calc(")?; }
conditional_block
jest.config.js
const config = require('./config.js'); module.exports = { moduleFileExtensions: ['js', 'jsx'], moduleNameMapper: {
'^_components/(.*)': '<rootDir>/components/$1', '^_containers/(.*)': '<rootDir>/webClient/containers/$1', '^_utils/(.*)': '<rootDir>/utils/$1', '^_jest/(.*)': '<rootDir>/jest/$1', '\\.(css|less)$': 'identity-obj-proxy', }, globals: Object.assign( { ROOT_DIR: '/', BUNDLE: 'webClie...
'^_webClient/(.*)': '<rootDir>/webClient/$1', '^_firebase/(.*)': '<rootDir>/firebase/$1', '^_store/(.*)': '<rootDir>/webClient/store/$1',
random_line_split
proto.py
SD_PROTO_VER = 0x02 SD_SHEEP_PROTO_VER = 0x0a SD_EC_MAX_STRIP = 16 SD_MAX_COPIES = SD_EC_MAX_STRIP * 2 - 1 SD_OP_CREATE_AND_WRITE_OBJ = 0x01 SD_OP_READ_OBJ = 0x02 SD_OP_WRITE_OBJ = 0x03 SD_OP_REMOVE_OBJ = 0x04 SD_OP_DISCARD_OBJ = 0x05 SD_OP_NEW_VDI = 0x11 SD_OP_LOCK_VDI = 0x12 SD_OP_R...
return VDI_BIT | vid << VDI_SPACE_SHIFT
identifier_body
proto.py
SD_PROTO_VER = 0x02 SD_SHEEP_PROTO_VER = 0x0a SD_EC_MAX_STRIP = 16 SD_MAX_COPIES = SD_EC_MAX_STRIP * 2 - 1 SD_OP_CREATE_AND_WRITE_OBJ = 0x01 SD_OP_READ_OBJ = 0x02 SD_OP_WRITE_OBJ = 0x03 SD_OP_REMOVE_OBJ = 0x04 SD_OP_DISCARD_OBJ = 0x05 SD_OP_NEW_VDI = 0x11 SD_OP_LOCK_VDI = 0x12 SD_OP_R...
(vid): return VDI_BIT | vid << VDI_SPACE_SHIFT
vid_to_vdi_oid
identifier_name
proto.py
SD_PROTO_VER = 0x02 SD_SHEEP_PROTO_VER = 0x0a SD_EC_MAX_STRIP = 16 SD_MAX_COPIES = SD_EC_MAX_STRIP * 2 - 1 SD_OP_CREATE_AND_WRITE_OBJ = 0x01 SD_OP_READ_OBJ = 0x02 SD_OP_WRITE_OBJ = 0x03 SD_OP_REMOVE_OBJ = 0x04 SD_OP_DISCARD_OBJ = 0x05 SD_OP_NEW_VDI = 0x11 SD_OP_LOCK_VDI = 0x12 SD_OP_R...
SD_OLD_MAX_VDI_SIZE = (SD_DATA_OBJ_SIZE * OLD_MAX_DATA_OBJS) SD_MAX_VDI_SIZE = (SD_DATA_OBJ_SIZE * MAX_DATA_OBJS) SD_DEFAULT_BLOCK_SIZE_SHIFT = 22 SD_LEDGER_OBJ_SIZE = 1 << 22 CURRENT_VDI_ID = 0 STORE_LEN = 16 SD_REQ_SIZE = 48 SD_RSP_SIZE = 48 LOCK_TYPE_NORMAL = 0 LOCK_TYPE_SHARED = 1 # for iSCSI multipath def v...
SD_MAX_SNAPSHOT_TAG_LEN = 256 SD_NR_VDIS = 1 << 24 SD_DATA_OBJ_SIZE = 1 << 22
random_line_split
main.rs
use std::fs; use std::io::prelude::*; use std::net::TcpListener; use std::net::TcpStream; // ANCHOR: here use std::thread; use std::time::Duration; // --snip-- // ANCHOR_END: here fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); for stream in listener.incoming() { let stream = ...
else { ("HTTP/1.1 404 NOT FOUND", "404.html") }; // --snip-- // ANCHOR_END: here let contents = fs::read_to_string(filename).unwrap(); let response = format!( "{}\r\nContent-Length: {}\r\n\r\n{}", status_line, contents.len(), contents ); stream.wr...
{ thread::sleep(Duration::from_secs(5)); ("HTTP/1.1 200 OK", "hello.html") }
conditional_block
main.rs
use std::fs; use std::io::prelude::*; use std::net::TcpListener; use std::net::TcpStream; // ANCHOR: here use std::thread; use std::time::Duration; // --snip-- // ANCHOR_END: here fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); for stream in listener.incoming() { let stream = ...
// ANCHOR_END: here let contents = fs::read_to_string(filename).unwrap(); let response = format!( "{}\r\nContent-Length: {}\r\n\r\n{}", status_line, contents.len(), contents ); stream.write(response.as_bytes()).unwrap(); stream.flush().unwrap(); // ANCHOR: ...
random_line_split
main.rs
use std::fs; use std::io::prelude::*; use std::net::TcpListener; use std::net::TcpStream; // ANCHOR: here use std::thread; use std::time::Duration; // --snip-- // ANCHOR_END: here fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); for stream in listener.incoming() { let stream = ...
// ANCHOR_END: here
{ // --snip-- // ANCHOR_END: here let mut buffer = [0; 1024]; stream.read(&mut buffer).unwrap(); // ANCHOR: here let get = b"GET / HTTP/1.1\r\n"; let sleep = b"GET /sleep HTTP/1.1\r\n"; let (status_line, filename) = if buffer.starts_with(get) { ("HTTP/1.1 200 OK", "hello.html"...
identifier_body
main.rs
use std::fs; use std::io::prelude::*; use std::net::TcpListener; use std::net::TcpStream; // ANCHOR: here use std::thread; use std::time::Duration; // --snip-- // ANCHOR_END: here fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); for stream in listener.incoming() { let stream = ...
(mut stream: TcpStream) { // --snip-- // ANCHOR_END: here let mut buffer = [0; 1024]; stream.read(&mut buffer).unwrap(); // ANCHOR: here let get = b"GET / HTTP/1.1\r\n"; let sleep = b"GET /sleep HTTP/1.1\r\n"; let (status_line, filename) = if buffer.starts_with(get) { ("HTTP/1...
handle_connection
identifier_name
setup.py
import versioneer import os
with open('requirements-optional.txt') as f: optionals = f.read().splitlines() reqs = [] for ir in required: if ir[0:3] == 'git': name = ir.split('/')[-1] reqs += ['%s @ %s@master' % (name, ir)] else: reqs += [ir] opt_reqs = [] extras_require = {} for ir in optionals: # For con...
from setuptools import setup, find_packages with open('requirements.txt') as f: required = f.read().splitlines()
random_line_split
setup.py
import versioneer import os from setuptools import setup, find_packages with open('requirements.txt') as f: required = f.read().splitlines() with open('requirements-optional.txt') as f: optionals = f.read().splitlines() reqs = [] for ir in required: if ir[0:3] == 'git': name = ir.split('/')[-1] ...
extras_require['extras'] = opt_reqs # If interested in benchmarking devito, we need the `examples` too exclude = ['docs', 'tests'] try: if not bool(int(os.environ.get('DEVITO_BENCHMARKS', 0))): exclude += ['examples'] except (TypeError, ValueError): exclude += ['examples'] setup(name='devito', ...
opt_reqs += [ir]
conditional_block
admin_crud_spec.ts
/* * Copyright 2022 ThoughtWorks, 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 applicable law or agr...
describe("admin crud", () => { beforeEach(() => jasmine.Ajax.install()); afterEach(() => jasmine.Ajax.uninstall()); describe("bulkUpdate", () => { const API_SYSTEM_ADMINS_PATH = "/go/api/admin/security/system_admins"; it("should make a patch request", (done) => { const bulkUpdateSystemAdmins = { ...
import {AdminsCRUD} from "models/admins/admin_crud";
random_line_split
fastclick.js
/** * @preserve FastClick: polyfill to remove click delays on browsers with touch UIs. * * @version 1.0.2 * @codingstandard ftlabs-jsv2 * @copyright The Financial Times Limited [All Rights Reserved] * @license MIT License (see LICENSE.txt) */ /*jslint browser:true, node:true*/ /*global define, Event, Node*/ /...
// Weird things happen on iOS when an alert or confirm dialog is opened from a click event callback (issue #23): // when the user next taps anywhere else on the page, new touchstart and touchend events are dispatched // with the same identifier as the touch event that previously triggered the click th...
random_line_split
fastclick.js
/** * @preserve FastClick: polyfill to remove click delays on browsers with touch UIs. * * @version 1.0.2 * @codingstandard ftlabs-jsv2 * @copyright The Financial Times Limited [All Rights Reserved] * @license MIT License (see LICENSE.txt) */ /*jslint browser:true, node:true*/ /*global define, Event, Node*/ /...
this.lastTouchIdentifier = touch.identifier; // If the target element is a child of a scrollable layer (using -webkit-overflow-scrolling: touch) and: // 1) the user does a fling scroll on the scrollable layer // 2) the user stops the fling scroll with another tap // then the event.targe...
{ event.preventDefault(); return false; }
conditional_block
fastclick.js
/** * @preserve FastClick: polyfill to remove click delays on browsers with touch UIs. * * @version 1.0.2 * @codingstandard ftlabs-jsv2 * @copyright The Financial Times Limited [All Rights Reserved] * @license MIT License (see LICENSE.txt) */ /*jslint browser:true, node:true*/ /*global define, Event, Node*/ /...
/** * Android requires exceptions. * * @type boolean */ var deviceIsAndroid = navigator.userAgent.indexOf('Android') > 0; /** * iOS requires exceptions. * * @type boolean */ var deviceIsIOS = /iP(ad|hone|od)/.test(navigator.userAgent); /** * iOS 4 requires an exception for select elements. * * @type b...
{ 'use strict'; var oldOnClick; options = options || {}; /** * Whether a click is currently being tracked. * * @type boolean */ this.trackingClick = false; /** * Timestamp for when click tracking started. * * @type number */ this.trackingClickStart = 0; /** * The element...
identifier_body
fastclick.js
/** * @preserve FastClick: polyfill to remove click delays on browsers with touch UIs. * * @version 1.0.2 * @codingstandard ftlabs-jsv2 * @copyright The Financial Times Limited [All Rights Reserved] * @license MIT License (see LICENSE.txt) */ /*jslint browser:true, node:true*/ /*global define, Event, Node*/ /...
(method, context) { return function() { return method.apply(context, arguments); }; } var methods = ['onMouse', 'onClick', 'onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel']; var context = this; for (var i = 0, l = methods.length; i < l; i++) { context[methods[i]] = bind(context[methods[i]]...
bind
identifier_name
command.rs
// Copyright 2014 The Gfx-rs Developers. // // 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 ag...
} /// Returns the mapped buffers that The GPU will read from pub fn mapped_reads(&self) -> AccessInfoBuffers<R> { self.mapped_reads.iter() } /// Returns the mapped buffers that The GPU will write to pub fn mapped_writes(&self) -> AccessInfoBuffers<R> { self.mapped_writes.iter(...
{ self.mapped_writes.insert(buffer.clone()); }
conditional_block
command.rs
// Copyright 2014 The Gfx-rs Developers. // // 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 ag...
fn generate_mipmap(&mut self, R::ShaderResourceView); /// Clear color target fn clear_color(&mut self, R::RenderTargetView, ClearColor); fn clear_depth_stencil(&mut self, R::DepthStencilView, Option<target::Depth>, Option<target::Stencil>); /// Draw a primitive fn call...
random_line_split
command.rs
// Copyright 2014 The Gfx-rs Developers. // // 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 ag...
/// Returns the mapped buffers that The GPU will write to pub fn mapped_writes(&self) -> AccessInfoBuffers<R> { self.mapped_writes.iter() } /// Is there any mapped buffer reads ? pub fn has_mapped_reads(&self) -> bool { !self.mapped_reads.is_empty() } /// Is there any map...
{ self.mapped_reads.iter() }
identifier_body
command.rs
// Copyright 2014 The Gfx-rs Developers. // // 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 ag...
(&self) -> bool { !self.mapped_writes.is_empty() } /// Takes all the accesses necessary for submission pub fn take_accesses(&self) -> SubmissionResult<AccessGuard<R>> { for buffer in self.mapped_reads().chain(self.mapped_writes()) { unsafe { if !buffer.mapping()....
has_mapped_writes
identifier_name
app.py
from flask import Flask app = Flask(__name__) from media import Movie from flask import render_template import re @app.route('/') def
(): '''View function for index page.''' toy_story = Movie(title = "Toy Story 3", trailer_youtube_url ="https://www.youtube.com/watch?v=QW0sjQFpXTU", poster_image_url="https://images-na.ssl-images-amazon.com/images/M/MV5BMTgxOTY4Mjc0MF5BMl5BanBnXkFtZTcwNTA4MDQyMw@@._V1_UY268_CR3,0,182,268_AL_.jpg", storyli...
index
identifier_name
app.py
from flask import Flask app = Flask(__name__) from media import Movie from flask import render_template import re @app.route('/') def index(): '''View function for index page.''' toy_story = Movie(title = "Toy Story 3", trailer_youtube_url ="https://www.youtube.com/watch?v=QW0sjQFpXTU", poster_image_url="https...
return render_template('index.html', data=movies) if __name__ == '__main__': app.run(debug=True)
youtube_id_match = re.search(r'(?<=v=)[^&#]+', movie.trailer_youtube_url) youtube_id_match = youtube_id_match or re.search(r'(?<=be/)[^&#]+', movie.trailer_youtube_url) trailer_youtube_id = (youtube_id_match.group(0) if youtube_id_match else None) movie.trailer_youtube_url = trailer_youtube_id
conditional_block
app.py
from flask import Flask app = Flask(__name__) from media import Movie from flask import render_template import re @app.route('/') def index(): '''View function for index page.'''
storyline='''Andy's toys get mistakenly delivered to a day care centre. Woody convinces the other toys that they weren't dumped and leads them on an expedition back home.''') pulp_fiction = Movie(title = "Pulp Fiction ", trailer_youtube_url ="https://www.youtube.com/watch?v=s7EdQ4FqbhY", ...
toy_story = Movie(title = "Toy Story 3", trailer_youtube_url ="https://www.youtube.com/watch?v=QW0sjQFpXTU", poster_image_url="https://images-na.ssl-images-amazon.com/images/M/MV5BMTgxOTY4Mjc0MF5BMl5BanBnXkFtZTcwNTA4MDQyMw@@._V1_UY268_CR3,0,182,268_AL_.jpg",
random_line_split
app.py
from flask import Flask app = Flask(__name__) from media import Movie from flask import render_template import re @app.route('/') def index():
if __name__ == '__main__': app.run(debug=True)
'''View function for index page.''' toy_story = Movie(title = "Toy Story 3", trailer_youtube_url ="https://www.youtube.com/watch?v=QW0sjQFpXTU", poster_image_url="https://images-na.ssl-images-amazon.com/images/M/MV5BMTgxOTY4Mjc0MF5BMl5BanBnXkFtZTcwNTA4MDQyMw@@._V1_UY268_CR3,0,182,268_AL_.jpg", storyline=''...
identifier_body
settings.py
# Django settings for imageuploads project. import os PROJECT_DIR = os.path.dirname(__file__) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql...
pass
try: execfile(os.path.join(os.path.dirname(__file__), "local_settings.py")) except IOError:
random_line_split
oauth.ts
import crypto from "crypto"; import oauth from "oauth-sign"; import { URL } from "url"; import { Credentials } from "./credentials"; // Object.fromEntries const objectFromEntries = ( entries: IterableIterator<[string, string]> ): { [key: string]: string } => { const o = Object.create(null); for (const [k, v] of ...
urlObject.protocol + "//" + urlObject.host + urlObject.pathname, objectFromEntries(urlObject.searchParams.entries()), oauthKeys.consumerSecret, oauthKeys.accessTokenSecret ), ], ] .map(([name, value]) => `${name}="${oauth.rfc3986(value)}"`) .join(","); return `OAuth...
"oauth_signature", oauth.sign( signatureMethod, method,
random_line_split
issue.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 frappe import json from frappe import _ from frappe import utils from frappe.model.document import Document from frappe.utils import now, time_di...
(self): communication = frappe.new_doc("Communication") communication.update({ "communication_type": "Communication", "communication_medium": "Email", "sent_or_received": "Received", "email_status": "Open", "subject": self.subject, "sender": self.raised_by, "content": self.description, "stat...
create_communication
identifier_name
issue.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 frappe import json from frappe import _ from frappe import utils from frappe.model.document import Document from frappe.utils import now, time_di...
def change_service_level_agreement_and_priority(self): if self.service_level_agreement and frappe.db.exists("Issue", self.name) and \ frappe.db.get_single_value("Support Settings", "track_service_level_agreement"): if not self.priority == frappe.db.get_value("Issue", self.name, "priority"): self.set_res...
service_level_agreement = get_active_service_level_agreement_for(priority=priority, customer=self.customer, service_level_agreement=service_level_agreement) if not service_level_agreement: if frappe.db.get_value("Issue", self.name, "service_level_agreement"): frappe.throw(_("Couldn't Set Service Level Agre...
identifier_body
issue.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 frappe import json from frappe import _ from frappe import utils from frappe.model.document import Document from frappe.utils import now, time_di...
doc.reference_name = replicated_issue.name doc.save(ignore_permissions=True) frappe.get_doc({ "doctype": "Comment", "comment_type": "Info", "reference_doctype": "Issue", "reference_name": replicated_issue.name, "content": " - Split the Issue from <a href='#Form/Issue/{0}'>{1}</a>".format(self.na...
for communication in communications: doc = frappe.get_doc("Communication", communication.name)
random_line_split
issue.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 frappe import json from frappe import _ from frappe import utils from frappe.model.document import Document from frappe.utils import now, time_di...
filters.append(("Issue", "customer", "=", customer)) if customer else filters.append(("Issue", "raised_by", "=", user)) ignore_permissions = True return get_list(doctype, txt, filters, limit_start, limit_page_length, ignore_permissions=ignore_permissions) @frappe.whitelist() def set_multiple_status(names, stat...
filters = []
conditional_block
IonPrettyTextWriter.ts
/*! * Copyright 2012 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in...
(incrementValue: number): void { this.indentCount = this.indentCount + incrementValue; if (this.indentSize && this.indentSize > 0) { for (let i = 0; i < this.indentCount * this.indentSize; i++) { this.writeable.writeByte(CharCodes.SPACE); } } } }
writePrettyIndent
identifier_name
IonPrettyTextWriter.ts
/*! * Copyright 2012 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in...
stepOut(): void { const currentContainer = this.containerContext.pop(); if (!currentContainer || !currentContainer.containerType) { throw new Error("Can't step out when not in a container"); } else if ( currentContainer.containerType === IonTypes.STRUCT && currentContainer.state === St...
{ if (type === undefined || type === null) { type = IonTypes.NULL; } this.handleSeparator(); this.writePrettyValue(); this.writeAnnotations(); this._writeNull(type); if (this.currentContainer.containerType === IonTypes.STRUCT) { this.currentContainer.state = State.STRUCT_FIELD; ...
identifier_body
IonPrettyTextWriter.ts
/*! * Copyright 2012 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in...
this.writeSymbolToken(fieldName); this.writeable.writeByte(CharCodes.COLON); this.writeable.writeByte(CharCodes.SPACE); this.currentContainer.state = State.VALUE; } writeNull(type: IonType): void { if (type === undefined || type === null) { type = IonTypes.NULL; } this.handleSepa...
this.writePrettyIndent(0);
random_line_split
item.py
#!/usr/bin/env python3 # Copyright (c) 2008-9 Qtrac Ltd. All rights reserved. # This program or module 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 2 of the License, or # version 3 of the Lic...
def setYear(self, year): self.__year = year def __str__(self): year = "" if self.__year is not None: year = " in {0}".format(self.__year) return "{0} by {1}{2}".format(self.__title, self.__artist, year) class Painting(Item): def __init__(self, artist, title, ...
return self.__year
random_line_split
item.py
#!/usr/bin/env python3 # Copyright (c) 2008-9 Qtrac Ltd. All rights reserved. # This program or module 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 2 of the License, or # version 3 of the Lic...
print("Sculptures use {0} unique materials".format( len(uniquematerials)))
uniquematerials.add(item.material())
conditional_block
item.py
#!/usr/bin/env python3 # Copyright (c) 2008-9 Qtrac Ltd. All rights reserved. # This program or module 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 2 of the License, or # version 3 of the Lic...
(self): raise NotImplemented def volume(self): raise NotImplemented if __name__ == "__main__": items = [] items.append(Painting("Cecil Collins", "The Poet", 1941)) items.append(Painting("Cecil Collins", "The Sleeping Fool", 1943)) items.append(Painting("Edvard Munch", "The Screa...
area
identifier_name
item.py
#!/usr/bin/env python3 # Copyright (c) 2008-9 Qtrac Ltd. All rights reserved. # This program or module 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 2 of the License, or # version 3 of the Lic...
class Dimension(object): def __init__(self, width, height, depth=None): self.__width = width self.__height = height self.__depth = depth def width(self): return self.__width def setWidth(self, width): self.__width = width def height(self): return...
def __init__(self, artist, title, year=None, material=None): super(Sculpture, self).__init__(artist, title, year) self.__material = material def material(self): return self.__material def setMaterial(self, material): self.__material = material def __str__(self): ...
identifier_body
unittest.py
#!/usr/bin/env python # ***** BEGIN LICENSE BLOCK ***** # 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/. # ***** END LICENSE BLOCK ***** import os import re from mozhar...
class EmulatorMixin(object): """ Currently dependent on both TooltoolMixin and TestingMixin)""" def install_emulator_from_tooltool(self, manifest_path): dirs = self.query_abs_dirs() if self.tooltool_fetch(manifest_path, output_dir=dirs['abs_work_dir']): self.fatal("Unable to down...
""" A class that extends OutputParser such that it can parse the number of passed/failed/todo tests from the output. """ def __init__(self, suite_category, **kwargs): # worst_log_level defined already in DesktopUnittestOutputParser # but is here to make pylint happy self.worst_l...
identifier_body
unittest.py
#!/usr/bin/env python # ***** BEGIN LICENSE BLOCK ***** # 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/. # ***** END LICENSE BLOCK ***** import os
from mozharness.base.log import OutputParser, WARNING, INFO, CRITICAL from mozharness.mozilla.buildbot import TBPL_WARNING, TBPL_FAILURE, TBPL_RETRY from mozharness.mozilla.buildbot import TBPL_SUCCESS, TBPL_WORST_LEVEL_TUPLE SUITE_CATEGORIES = ['mochitest', 'reftest', 'xpcshell'] def tbox_print_summary(pass_count, ...
import re from mozharness.mozilla.testing.errors import TinderBoxPrintRe
random_line_split
unittest.py
#!/usr/bin/env python # ***** BEGIN LICENSE BLOCK ***** # 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/. # ***** END LICENSE BLOCK ***** import os import re from mozhar...
elif self.config.get('emulator_manifest'): manifest_path = self.create_tooltool_manifest(self.config['emulator_manifest']) self.install_emulator_from_tooltool(manifest_path) elif self.buildbot_config: props = self.buildbot_config.get('properties') url = '...
self._download_unzip(self.config['emulator_url'], dirs['abs_emulator_dir'])
conditional_block
unittest.py
#!/usr/bin/env python # ***** BEGIN LICENSE BLOCK ***** # 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/. # ***** END LICENSE BLOCK ***** import os import re from mozhar...
(self, suite_name): # We are duplicating a condition (fail_count) from evaluate_parser and # parse parse_single_line but at little cost since we are not parsing # the log more then once. I figured this method should stay isolated as # it is only here for tbpl highlighted summaries and i...
append_tinderboxprint_line
identifier_name
crypto-list.ts
import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; @IonicPage() @Component({ selector: 'page-crypto-list', templateUrl: 'crypto-list.html', }) export class CryptoListPage { data = [ { id: 'bitcoin', name: 'Bitcoin', symbol: 'btc',...
symbol: 'ltc', rank: '5', price_usd: '263.913', percent_change_1h: '2.21' } ]; constructor(public navCtrl: NavController, public navParams: NavParams) {} precision(n,m) { return parseFloat(n).toFixed(m); } evolution(n) { return n > 0 ? '<span>' + parseFloat(n).toFi...
random_line_split
crypto-list.ts
import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; @IonicPage() @Component({ selector: 'page-crypto-list', templateUrl: 'crypto-list.html', }) export class CryptoListPage { data = [ { id: 'bitcoin', name: 'Bitcoin', symbol: 'btc',...
(n) { return n > 0 ? '<span>' + parseFloat(n).toFixed(2) + '&nbsp;<i class="fa fa-caret-up"></i></span>' : '<span class="red">' + parseFloat(n).toFixed(2) + '&nbsp;<i class="fa fa-caret-down"></i></span>'; } }
evolution
identifier_name
trivial_client.py
from __future__ import print_function import time import argparse import grpc from jaeger_client import Config from grpc_opentracing import open_tracing_client_interceptor from grpc_opentracing.grpcext import intercept_channel import command_line_pb2 def run(): parser = argparse.ArgumentParser() parser.ad...
}, service_name='trivial-client') tracer = config.initialize_tracer() tracer_interceptor = open_tracing_client_interceptor( tracer, log_payloads=args.log_payloads) channel = grpc.insecure_channel('localhost:50051') channel = intercept_channel(channel, tracer_interceptor) stub...
}, 'logging': True,
random_line_split
trivial_client.py
from __future__ import print_function import time import argparse import grpc from jaeger_client import Config from grpc_opentracing import open_tracing_client_interceptor from grpc_opentracing.grpcext import intercept_channel import command_line_pb2 def
(): parser = argparse.ArgumentParser() parser.add_argument( '--log_payloads', action='store_true', help='log request/response objects to open-tracing spans') args = parser.parse_args() config = Config( config={ 'sampler': { 'type': 'const', ...
run
identifier_name
trivial_client.py
from __future__ import print_function import time import argparse import grpc from jaeger_client import Config from grpc_opentracing import open_tracing_client_interceptor from grpc_opentracing.grpcext import intercept_channel import command_line_pb2 def run(): parser = argparse.ArgumentParser() parser.ad...
run()
conditional_block
trivial_client.py
from __future__ import print_function import time import argparse import grpc from jaeger_client import Config from grpc_opentracing import open_tracing_client_interceptor from grpc_opentracing.grpcext import intercept_channel import command_line_pb2 def run():
if __name__ == '__main__': run()
parser = argparse.ArgumentParser() parser.add_argument( '--log_payloads', action='store_true', help='log request/response objects to open-tracing spans') args = parser.parse_args() config = Config( config={ 'sampler': { 'type': 'const', ...
identifier_body
transmission.rs
//! A minimal implementation of rpc client for Tranmission. use reqwest::header::HeaderValue; use reqwest::{self, Client, IntoUrl, StatusCode, Url}; use serde_json::Value; use std::{fmt, result}; pub type Result<T> = result::Result<T, failure::Error>;
#[fail(display = "failed to get SessionId from header")] SessionIdNotFound, #[fail(display = "unexpected status code: {}", status)] UnexpectedStatus { status: reqwest::StatusCode }, #[fail(display = "the transmission server responded with an error: {}", error)] ResponseError { error: String }, }...
#[derive(Debug, Fail)] enum TransmissionError {
random_line_split
transmission.rs
//! A minimal implementation of rpc client for Tranmission. use reqwest::header::HeaderValue; use reqwest::{self, Client, IntoUrl, StatusCode, Url}; use serde_json::Value; use std::{fmt, result}; pub type Result<T> = result::Result<T, failure::Error>; #[derive(Debug, Fail)] enum TransmissionError { #[fail(display...
; let url = url.into_url()?; let http_client = Client::new(); let sid = http_client .get(url.clone()) .send()? .headers() .get("X-Transmission-Session-Id") .ok_or(TransmissionError::SessionIdNotFound)? .clone(); Ok(S...
{ None }
conditional_block
transmission.rs
//! A minimal implementation of rpc client for Tranmission. use reqwest::header::HeaderValue; use reqwest::{self, Client, IntoUrl, StatusCode, Url}; use serde_json::Value; use std::{fmt, result}; pub type Result<T> = result::Result<T, failure::Error>; #[derive(Debug, Fail)] enum TransmissionError { #[fail(display...
<U>(url: U, user: Option<(String, String)>) -> Result<Self> where U: IntoUrl, { let user = if let Some((n, p)) = user { Some(User { name: n, password: p, }) } else { None }; let url = url.into_url()?; ...
new
identifier_name
js-let-vs-var.js
"use strict"; var a = 1; let b = 1; console.log("after global declaration", a, b); function asdf() { var a = 2; let b = 2; console.log("in method asdf", a, b); } console.log("after function declaration", a, b); asdf(); console.log("after function call", a, b) if(true) { var a = 3; let b = 3; console....
// the same sample with let for (let i = 0; i < items.length; i++) { setTimeout(function () { console.log("logging item with index %d using let, %s: %s", i, items, items[i]); }, 10); }
{ setTimeout(function () { console.log("logging item with index %d using var, %s: %s", i, items, items[i]); }, 10); }
conditional_block
js-let-vs-var.js
"use strict"; var a = 1; let b = 1; console.log("after global declaration", a, b); function asdf() { var a = 2; let b = 2; console.log("in method asdf", a, b); } console.log("after function declaration", a, b); asdf(); console.log("after function call", a, b) if(true) { var a = 3; let b = 3; console....
console.log("---"); var items = [1,2,3,4] for (var i = 0; i < items.length; i++) { setTimeout(function () { console.log("logging item with index %d using var, %s: %s", i, items, items[i]); }, 10); } // the same sample with let for (let i = 0; i < items.length; i++) { setTimeout(function () { console.l...
random_line_split
js-let-vs-var.js
"use strict"; var a = 1; let b = 1; console.log("after global declaration", a, b); function
() { var a = 2; let b = 2; console.log("in method asdf", a, b); } console.log("after function declaration", a, b); asdf(); console.log("after function call", a, b) if(true) { var a = 3; let b = 3; console.log("in if block", a, b); } console.log("after if block", a, b); console.log("---"); var items =...
asdf
identifier_name
js-let-vs-var.js
"use strict"; var a = 1; let b = 1; console.log("after global declaration", a, b); function asdf()
console.log("after function declaration", a, b); asdf(); console.log("after function call", a, b) if(true) { var a = 3; let b = 3; console.log("in if block", a, b); } console.log("after if block", a, b); console.log("---"); var items = [1,2,3,4] for (var i = 0; i < items.length; i++) { setTimeout(functi...
{ var a = 2; let b = 2; console.log("in method asdf", a, b); }
identifier_body
SubTitlesComponent.tsx
import * as React from 'react'; import * as ReactDOM from 'react-dom'; import CursorDispOffset from '../CursorDispOffset'; import ChatStatusSender from '../../../Contents/Sender/ChatStatusSender'; interface SubTitlesProp { chat: ChatStatusSender; offset: CursorDispOffset; } /** * 字幕表示メイン */ export defaul...
* 字幕表示のスタイル情報 */ private GetStyle() { let offset = this.props.offset; let bottompos = Math.round((offset.clientHeight - offset.dispHeight) / 2); let sidepos = Math.round((offset.clientWidth - offset.dispWidth) / 2); let fontsize = Math.round((offset.dispHeight + offset.dispWid...
sg = ""; if (this.props.chat.message) { msg = this.props.chat.message; } if (msg == null || msg.length == 0) { return (<div></div>); } else { return ( <div id='sbj-cast-subtitles' className='sbj-cast-subtitles' style={this.Get...
identifier_body
SubTitlesComponent.tsx
import * as React from 'react'; import * as ReactDOM from 'react-dom'; import CursorDispOffset from '../CursorDispOffset'; import ChatStatusSender from '../../../Contents/Sender/ChatStatusSender'; interface SubTitlesProp { chat: ChatStatusSender; offset: CursorDispOffset; } /** * 字幕表示メイン */ export defaul...
right: sidepos.toString() + "px", fontSize: fontsize.toString() + "px", lineHeight: lineheight.toString() + "px", }; } }
random_line_split
SubTitlesComponent.tsx
import * as React from 'react'; import * as ReactDOM from 'react-dom'; import CursorDispOffset from '../CursorDispOffset'; import ChatStatusSender from '../../../Contents/Sender/ChatStatusSender'; interface SubTitlesProp { chat: ChatStatusSender; offset: CursorDispOffset; } /** * 字幕表示メイン */ export defaul...
g == null || msg.length == 0) { return (<div></div>); } else { return ( <div id='sbj-cast-subtitles' className='sbj-cast-subtitles' style={this.GetStyle()}> {msg} </div> ); } } /** * 字幕表示のスタイル情...
g = this.props.chat.message; } if (ms
conditional_block
SubTitlesComponent.tsx
import * as React from 'react'; import * as ReactDOM from 'react-dom'; import CursorDispOffset from '../CursorDispOffset'; import ChatStatusSender from '../../../Contents/Sender/ChatStatusSender'; interface SubTitlesProp { chat: ChatStatusSender; offset: CursorDispOffset; } /** * 字幕表示メイン */ export defaul...
t msg = ""; if (this.props.chat.message) { msg = this.props.chat.message; } if (msg == null || msg.length == 0) { return (<div></div>); } else { return ( <div id='sbj-cast-subtitles' className='sbj-cast-subtitles' style={this....
le
identifier_name
brushTypes.js
SyntaxHighlighter.autoloader( 'xs ' + MTBrushParams.baseUrl + '/shBrushXSScript.js' ); // disable double click to select SyntaxHighlighter.defaults['quick-code'] = false; // add toolbar related code // function selectElementText(el, win) { win = win || window; var doc = win.document, se...
() { if (window.getSelection) { if (window.getSelection().empty) { // Chrome window.getSelection().empty(); } else if (window.getSelection().removeAllRanges) { // Firefox window.getSelection().removeAllRanges(); } } else if (document.selection) { // IE? ...
clearSelection
identifier_name
brushTypes.js
SyntaxHighlighter.autoloader( 'xs ' + MTBrushParams.baseUrl + '/shBrushXSScript.js' ); // disable double click to select SyntaxHighlighter.defaults['quick-code'] = false; // add toolbar related code // function selectElementText(el, win) { win = win || window; var doc = win.document, se...
ert('請按Ctrl+C來複製程式碼。'); } } } }; SyntaxHighlighter.all();
clearSelection(); alert('程式碼已經成功複製到剪貼簿。'); } else { al
conditional_block
brushTypes.js
SyntaxHighlighter.autoloader( 'xs ' + MTBrushParams.baseUrl + '/shBrushXSScript.js' ); // disable double click to select SyntaxHighlighter.defaults['quick-code'] = false; // add toolbar related code // function selectElementText(el, win) { win = win || window; var doc = win.document, se...
SyntaxHighlighter.config["strings"]["copy"] = "複製程式碼"; SyntaxHighlighter.toolbar["items"]["list"] = ['copy']; SyntaxHighlighter.toolbar["items"]["copy"] = { execute: function(highlighter) { var div = $("#highlighter_" + highlighter.id); var container = div.find(".container"); if (container...
{ if (window.getSelection) { if (window.getSelection().empty) { // Chrome window.getSelection().empty(); } else if (window.getSelection().removeAllRanges) { // Firefox window.getSelection().removeAllRanges(); } } else if (document.selection) { // IE? do...
identifier_body
brushTypes.js
SyntaxHighlighter.autoloader( 'xs ' + MTBrushParams.baseUrl + '/shBrushXSScript.js' ); // disable double click to select SyntaxHighlighter.defaults['quick-code'] = false; // add toolbar related code // function selectElementText(el, win) { win = win || window;
sel.removeAllRanges(); sel.addRange(range); } else if (doc.body.createTextRange) { range = doc.body.createTextRange(); range.moveToElementText(el); range.select(); } } function clearSelection() { if (window.getSelection) { if (window.getSelection().empty) { ...
var doc = win.document, sel, range; if (win.getSelection && doc.createRange) { sel = win.getSelection(); range = doc.createRange(); range.selectNodeContents(el);
random_line_split
game.py
# Copyright 2010, 2014 Gerardo Marset <gammer1994@gmail.com> # # This file is part of Haxxor Engine. # # Haxxor Engine 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 versi...
(object): def __init__(self): self.running = True print("Bienvenido a Haxxor Engine.") try: self.name = "test" if tools.DEBUG else ask_for_name() except EOFError: self.running = False return self.clear() if os.path.isfile(SAVEGAM...
Game
identifier_name
game.py
# Copyright 2010, 2014 Gerardo Marset <gammer1994@gmail.com> # # This file is part of Haxxor Engine. # # Haxxor Engine 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 versi...
for element in recursive_loop(filesystem): pass self.system = system.System(filesystem, ip, True) def save(self): with open(SAVEGAME.format(self.name), "w") as f: f.write(json.dumps({ "aliases": self.aliases, "mission_id": self.mission_id...
sinstance(value, dict): for element in recursive_loop(value): pass else: directory[name] = File(value) yield name
conditional_block
game.py
# Copyright 2010, 2014 Gerardo Marset <gammer1994@gmail.com> # # This file is part of Haxxor Engine. # # Haxxor Engine 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 versi...
ask_for_name(): while True: name = tools.iinput("¿Cuál es tu nombre? ") if name == "": print("Escribí tu nombre.") continue if not all(ord(c) < 128 for c in name): print("Solo se permiten caracteres ASCII.") continue if not name.isal...
{ "cd..": "cd ..", "ls": "dir", "rm": "del", "clear": "cls" } def
identifier_body
game.py
# Copyright 2010, 2014 Gerardo Marset <gammer1994@gmail.com> # # This file is part of Haxxor Engine. # # Haxxor Engine 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 versi...
SAVEGAME = "{}.sav" DOWNLOADS_DIR = "C:\\Descargas" class Game(object): def __init__(self): self.running = True print("Bienvenido a Haxxor Engine.") try: self.name = "test" if tools.DEBUG else ask_for_name() except EOFError: self.running = False ...
import cli import system import missions
random_line_split
test_list.py
import sys import unittest from test import test_support, list_tests class ListTest(list_tests.CommonTest): type2test = list def test_basic(self): self.assertEqual(list([]), []) l0_3 = [0, 1, 2, 3] l0_3_bis = list(l0_3) self.assertEqual(l0_3, l0_3_bis) self.assertTrue(l...
# This code used to segfault in Py2.4a3 x = [] x.extend(-y for y in x) self.assertEqual(x, []) def test_truth(self): super(ListTest, self).test_truth() self.assertTrue(not []) self.assertTrue([42]) def test_identity(self): self.assertTrue([] is...
self.assertRaises(MemoryError, list, xrange(sys.maxint // 2))
conditional_block